Hibernate的一个问题object references an unsaved transient instance - save the transi5
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(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。