如何使用Hibernate Annotations在Pojo类和抽象类之间建立一个has-a-relationship连接

时间:2011-08-05 08:45:20

标签: java hibernate annotations

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

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     公共类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对象,也无法保存数据。它不是关于hibernate配置文件,因为我在不同的场景中尝试过它。任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

将@Inheritance注释添加到B类。 您还可以使用策略值(如

)定义使用@inheritance注释为继承的类创建哪种类型表
@Inherintace(strategty = InheritanceType.TABLE_PER_CLASS)

编辑:

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

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

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