如何使用 Hibernate Annotations 在 Pojo 类和抽象类之间建立关系连接

发布于 2024-11-28 07:50:02 字数 6186 浏览 0 评论 0原文

我有一个名为 Driver.Java 的类、另一个名为 Truck.Java 的类和一个名为 Vehicle.Java 的抽象类。一个司机可以驾驶多辆车,卡车,公共汽车等。我想模拟这种情况。 Driver.Class 和 Vehicle.Class 通过 has-a 关系相互连接。代码如下。

Driver.Java

@Entity
@Table(name="DRIVER")

public class Driver {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private int driverId;

@OneToOne(cascade=CascadeType.ALL)
private Vehicle vehicle;

@Column(name="NAME")
private String name;

@Column(name="AGE")
private int age;

public Vehicle getVehicle() {
    return vehicle;
}
public void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public Driver(String name, int age) {
    this.name = name;
    this.age = age;
}
public void setDriverId(int driverId) {
    this.driverId = driverId;
}
public int getDriverId() {
    return driverId;
}

Vehicle.Java

@MappedSuperclass
public abstract class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private int id;

@Column(name="BRAND")
private String brand;

@Column(name="COLOUR")
private String colour;

@Column(name="PRICE")
private int price;

public String getBrand() {
    return brand;
}
public void setBrand(String brand) {
    this.brand = brand;
}
public String getColour() {
    return colour;
}
public void setColour(String colour) {
    this.colour = colour;
}
public int getPrice() {
    return price;
}
public void setPrice(int amount) {
    this.price = amount;
}

public abstract int totalCost();
public Vehicle(String brand, String colour, int price) {
    this.brand = brand;
    this.colour = colour;
    this.price = price;
}
public void setId(int id) {
    this.id = id;
}
public int getId() {
    return id;
}

public Vehicle(){}  
}

    Vehicle vehicle2 = new Truck("Mercedes", "White", 250);
    Driver driver = new Driver("Hakan Namlı", 36);
    driver.setVehicle(vehicle2);
    DriverDAO dDao = new DriverDAO();
    dDao.addDriver(driver); 

DriverDAO.Java

public class DriverDAO {

private Session session;

public void addDriver(Driver driver){

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        session.save(driver);
        session.getTransaction().commit();
    }
    catch(HibernateException ex){
        session.getTransaction().rollback();
        ex.printStackTrace();
    }
    finally{
        session.close();
    }
}
}

HibernateUTIL.Java public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
    try {
        sessionFactory = new AnnotationConfiguration()
        .configure()
        .addPackage("models") 
        .addAnnotatedClass(Driver.class)
        .addAnnotatedClass(Vehicle.class)
        .addAnnotatedClass(Truck.class)
        .addAnnotatedClass(Bus.class)
        .buildSessionFactory();

    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}

hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property      
     name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.url">...</property>
    <property name="hibernate.connection.username">...</property>
    <property name="hibernate.connection.password">...</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>   
</session-factory>

这是输出:

1 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.5.2-Final
11 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.2-Final
12 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
14 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
17 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
75 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
79 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
79 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
128 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
128 [main] INFO org.hibernate.cfg.AnnotationConfiguration - Mapping package models
146 [main] WARN org.hibernate.cfg.AnnotationBinder - Package not found or wo package-info.java: models
154 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
177 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Driver
201 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Driver on table DRIVER
238 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Truck
239 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Truck on table TRUCK
241 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Bus
241 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Bus on table BUS
Exception in thread "main" java.lang.NullPointerException
    at dao.DriverDAO.addDriver(DriverDAO.java:28)
    at main.Main.main(Main.java:39)

当我尝试运行它时,SessionFactory 类的对象返回 null。因此,我无法生成 Session 对象,也无法保存数据。这与休眠配置文件无关,因为我在不同的场景中尝试过它。任何帮助将不胜感激。谢谢。

I have a class named Driver.Java, another class named Truck.Java and an abstract class named Vehicle.Java. A driver can drive several vehicles, truck, bus etc. I want to simulate this situation. Driver.Class and Vehicle.Class connects each other with has-a-relationship. Codes are below.

Driver.Java

@Entity
@Table(name="DRIVER")

public class Driver {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private int driverId;

@OneToOne(cascade=CascadeType.ALL)
private Vehicle vehicle;

@Column(name="NAME")
private String name;

@Column(name="AGE")
private int age;

public Vehicle getVehicle() {
    return vehicle;
}
public void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public Driver(String name, int age) {
    this.name = name;
    this.age = age;
}
public void setDriverId(int driverId) {
    this.driverId = driverId;
}
public int getDriverId() {
    return driverId;
}

Vehicle.Java

@MappedSuperclass
public abstract class Vehicle {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="ID")
private int id;

@Column(name="BRAND")
private String brand;

@Column(name="COLOUR")
private String colour;

@Column(name="PRICE")
private int price;

public String getBrand() {
    return brand;
}
public void setBrand(String brand) {
    this.brand = brand;
}
public String getColour() {
    return colour;
}
public void setColour(String colour) {
    this.colour = colour;
}
public int getPrice() {
    return price;
}
public void setPrice(int amount) {
    this.price = amount;
}

public abstract int totalCost();
public Vehicle(String brand, String colour, int price) {
    this.brand = brand;
    this.colour = colour;
    this.price = price;
}
public void setId(int id) {
    this.id = id;
}
public int getId() {
    return id;
}

public Vehicle(){}  
}

Main

    Vehicle vehicle2 = new Truck("Mercedes", "White", 250);
    Driver driver = new Driver("Hakan Namlı", 36);
    driver.setVehicle(vehicle2);
    DriverDAO dDao = new DriverDAO();
    dDao.addDriver(driver); 

DriverDAO.Java

public class DriverDAO {

private Session session;

public void addDriver(Driver driver){

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.getTransaction().begin();
        session.save(driver);
        session.getTransaction().commit();
    }
    catch(HibernateException ex){
        session.getTransaction().rollback();
        ex.printStackTrace();
    }
    finally{
        session.close();
    }
}
}

HibernateUTIL.Java
public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
    try {
        sessionFactory = new AnnotationConfiguration()
        .configure()
        .addPackage("models") 
        .addAnnotatedClass(Driver.class)
        .addAnnotatedClass(Vehicle.class)
        .addAnnotatedClass(Truck.class)
        .addAnnotatedClass(Bus.class)
        .buildSessionFactory();

    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}

hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property      
     name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="hibernate.connection.url">...</property>
    <property name="hibernate.connection.username">...</property>
    <property name="hibernate.connection.password">...</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.OracleDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>   
</session-factory>

This is the output:

1 [main] INFO org.hibernate.cfg.annotations.Version - Hibernate Annotations 3.5.2-Final
11 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.5.2-Final
12 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
14 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
17 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
75 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
79 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
79 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
128 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null
128 [main] INFO org.hibernate.cfg.AnnotationConfiguration - Mapping package models
146 [main] WARN org.hibernate.cfg.AnnotationBinder - Package not found or wo package-info.java: models
154 [main] INFO org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
177 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Driver
201 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Driver on table DRIVER
238 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Truck
239 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Truck on table TRUCK
241 [main] INFO org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: models.Bus
241 [main] INFO org.hibernate.cfg.annotations.EntityBinder - Bind entity models.Bus on table BUS
Exception in thread "main" java.lang.NullPointerException
    at dao.DriverDAO.addDriver(DriverDAO.java:28)
    at main.Main.main(Main.java:39)

When i try to run this, object of SessionFactory class is returned null. So, i cannot generate a Session object and cannot save the data. It is not about hibernate config file, because i tried it in different scenarios. Any help will be appreciated. Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千秋岁 2024-12-05 07:50:02

为B类添加@Inheritance注解。
您还可以通过使用策略值(如

@Inherintace(strategty = InheritanceType.TABLE_PER_CLASS)

编辑)来定义为带有 @inheritance 注释的继承类创建哪种类型的表:

当您使用 new 关键字创建 DriverDAO 对象时,它的所有属性都只有默认值,并且所有对象都为 null。
您应该使用正确的值初始化 dDAO 对象

DriverDAO dDAO = new DriverDAOImpl();
dDAO.setSessionFactory(sessionFactory);

,或者如果您在构造函数中初始化 DriverDAO,请提供该代码。实体类与这个问题无关。

Add @Inheritance annotation to class B.
You can also define which kind table is created for inherised class with @inheritance annotation by using strategy value like

@Inherintace(strategty = InheritanceType.TABLE_PER_CLASS)

EDIT:

When you create your DriverDAO object with new keyword all it's attributes are has only defaul values and for all objects that is null.
You should initialize dDAO object with correct values

DriverDAO dDAO = new DriverDAOImpl();
dDAO.setSessionFactory(sessionFactory);

Or if you initialize DriverDAO in constructor please provide that code. Entity classes has nothing to do with this problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文