问题
I am using hibernate 4.1.10.Final to insert data into database, but it throws the following exception,
I have three tables, development and address .
Development has an object of address in itself.
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
INFO: HHH000412: Hibernate Core {4.1.10.Final}
INFO: HHH000206: hibernate.properties not found
INFO: HHH000021: Bytecode provider name : javassist
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
INFO: HHH000041: Configured SessionFactory: null
SEVERE: java.lang.NullPointerException
at org.hibernate.mapping.PersistentClass.createPrimaryKey(PersistentClass.java:327)
at org.hibernate.cfg.CreateKeySecondPass.doSecondPass(CreateKeySecondPass.java:48)
at org.hibernate.cfg.Configuration.processSecondPassesOfType(Configuration.java:1386)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1341)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1730)
at com.myproject.util.HibernateUtil.configureSessionFactory(HibernateUtil.java:23)
at com.myproject.util.HibernateUtil.getSessionFactory(HibernateUtil.java:34)
at com.myproject.model.ConstructionModel.addDevelopment(ConstructionModel.java:185)
at com.myproject.controller.Construction.addDevelopment(Construction.java:135)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
......
My code
development.java
@Entity
@Table(name="development")
public class Development implements Serializable{
private int id;
private Address address;
public Development(){
}
@Id
@GeneratedValue
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
address.java
@Entity
@Table(name="address")
public class Address implements Serializable{
private int id;
private String unit;
public Address(){
}
@Id
@GeneratedValue
@OneToOne(mappedBy="address")
@JoinColumn(name="addid")
public int getId() {
return id;
}
@Column (name="unit")
public String getUnit() {
return unit;
}
public void setId(int id) {
this.id = id;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
回答1:
Remove @GeneratedValue @OneToOne(mappedBy="development") @JoinColumn(name="Developer")
and @GeneratedValue @OneToOne(mappedBy="address") @JoinColumn(name="addid")
from Id fields of Developer and Address.
来源:https://stackoverflow.com/questions/17037949/how-to-insert-using-hibernate-4-1-10-final