У меня есть класс с именем Driver.Java, другой класс с именем Truck.Java и абстрактный класс с именем Vehicle.Java.Водитель может управлять несколькими транспортными средствами, грузовиком, автобусом и т. Д. Я хочу смоделировать эту ситуацию.Driver.Class и Vehicle.Class связывают друг друга с помощью отношения «имеет отношение».Коды указаны ниже.
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 открытый класс 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, потому что я пробовал его в разных сценариях.Любая помощь будет оценена.Спасибо.