一段时间不用了,纯属记录,以防忘记了。。。
在hibernate中,多对多关系可以看成是2个 多对一的关系。
在实体UserInfo和Teacher中,都设置many-to-many属性,
属性中需要设置主控方与被控方的inverse和cascade值
出现问题:save the transient instance before flushing
说明:t_s表,不需要单独建实体对象,是一张表
1 CREATE TABLE t_s 2 ( 3 u_id integer NOT NULL, 4 t_id integer NOT NULL, 5 CONSTRAINT t_s_pkey PRIMARY KEY (u_id, t_id), 6 CONSTRAINT t_s_t_id_fkey FOREIGN KEY (t_id) 7 REFERENCES teacher (id) MATCH SIMPLE 8 ON UPDATE NO ACTION ON DELETE NO ACTION, 9 CONSTRAINT t_s_u_id_fkey FOREIGN KEY (u_id) 10 REFERENCES userinfo (id) MATCH SIMPLE 11 ON UPDATE NO ACTION ON DELETE NO ACTION 12 )
UserInfo.hbm.cfg
1 <set name="teachers" table="t_s" inverse="false" cascade="all"> 2 <key column ="u_id"></key> 3 <many-to-many class="Teacher" column="t_id"></many-to-many> 4 </set>
Teacher.hbm.cfg
1 <set name="students" table="t_s" inverse="true" cascade="all"> 2 <key column ="t_id"></key> 3 <many-to-many class="UserInfo" column="u_id"></many-to-many> 4 </set>
测试代码:(*主控方与被控方的设置,先设主控方,在设被控方)
1 ///多对多操作 2 private static void ManyToMany() 3 { 4 Session session=HibernateUnit.getSession(); 5 session.beginTransaction(); 6 7 UserInfo u1=new UserInfo(); 8 UserInfo u2=new UserInfo(); 9 10 Teacher t1=new Teacher(); 11 Teacher t2=new Teacher(); 12 13 u1.setUsername("CC"); 14 u1.setAge(20); 15 u1.setAddress("1111"); 16 u1.setCg(null); 17 18 u2.setUsername("MR"); 19 u2.setAge(20); 20 u2.setAddress("1111"); 21 u2.setCg(null); 22 23 t1.setName("JiangRR"); 24 t2.setName("ChenXD"); 25 26 u1.getTeachers().add(t1); 27 u2.getTeachers().add(t2); 28 t1.getStudents().add(u1); 29 t2.getStudents().add(u2); 30 31 session.save(u1); 32 session.save(u2); 33 34 session.getTransaction().commit(); 35 }
测试效果:
1 Hibernate: select nextval ('userinfo_id_seq') 2 Hibernate: select nextval ('teacher_id_seq') 3 Hibernate: select nextval ('userinfo_id_seq') 4 Hibernate: select nextval ('teacher_id_seq') 5 Hibernate: insert into userinfo (username, age, address, id) values (?, ?, ?, ?) 6 Hibernate: insert into teacher (username, id) values (?, ?) 7 Hibernate: insert into userinfo (username, age, address, id) values (?, ?, ?, ?) 8 Hibernate: insert into teacher (username, id) values (?, ?) 9 Hibernate: insert into t_s (u_id, t_id) values (?, ?) 10 Hibernate: insert into t_s (u_id, t_id) values (?, ?)