1 我做了一对多和多对一的双向关联关系,在User这一方@ManyToOne已经设置了级联Cascade,这样在测试程序中保存User时,Group也应该自动保存,为什么会抛出以下的异常: (我是按着视频教程里的例子一步一步做的,但视频里却没有异常,是什么原因?)
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.bjsxt.hibernate.model.Group
2.如果在测试程序中 HibernateORMappingTest.java:在保存User之前,先把Group也保存了,即加上这一句s.save(g); 就不会出现异常了。可是视频教程里没有这一句,只是设置Cascade级联, 却能通过,这是什么原因呢。
User.java:
@Entity
@Table(name="t_user")
public class User {
private int id;
private String name;
private Group group; @ManyToOne(cascade={CascadeType.ALL} ) //Cascade设置级联
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} Group.java
@Entity
@Table(name ="t_group")
public class Group {
private int id;
private String name;
private Set<User> users = new HashSet<User>();
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} @OneToMany(mappedBy="group")
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
} 测试程序 HibernateORMappingTest.java:
public class HibernateORMappingTest { private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
sessionFactory= new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass(){
sessionFactory.close();
}
@Test
public void testSaveUser(){
User u = new User();
u.setName("u1");
Group g = new Group();
g.setName("g1");
u.setGroup(g);
Session s= sessionFactory.getCurrentSession();
s.beginTransaction();
//s.save(g); 加上这一句,就不报错了,可是视频教程里没这一句,只是设置了级联Cascade却能通过
s.save(u);
s.getTransaction().commit();
}
@Test
public void testSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
public static void main(String[] args){
beforeClass();
}
}