Hibernate inverse
inverse主要用在一对多和多对多双向关联上,可以被设置到集合标签<set>上,默认inverse为false。
inverse只对set+one-to-many或many-to-many有效,对many-to-one, one-to-one无效。
hibernate 一对多 单向
classes---->student (one--->many)
类:
one
public class Classes { private Integer id; private String name; private Set students; }
many
public class Student {//不用动 private Integer id; private String name; }
hbm.xml
Classes.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.model"> <class name="Classes" table="classes" > <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="name" column="name" type="java.lang.String" /> <set name="students"> <key column="class_id" /> <one-to-many class="com.model.Student" /> </set> </class> </hibernate-mapping>
Student.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.zd.model"> <class name="Student" table="student" > <id name="id" column="id" type="java.lang.Integer"> <generator class="native" /> </id> <property name="name" column="name" length="50" type="java.lang.String" /> </class> </hibernate-mapping>
测试用例
import java.util.HashSet; import java.util.Iterator; import java.util.Set; import junit.framework.TestCase; import org.hibernate.Session; import org.hibernate.Transaction; import com.model.Classes; import com.model.Student; public class OneToManyTest extends TestCase { public void testSave1(){ Session session = null; Transaction ta = null; try{ session = HibernateUtil.getSession(); ta = session.beginTransaction(); Student stu1 = new Student(); stu1.setName("z3"); Student stu2 = new Student(); stu2.setName("l4"); session.save(stu1); //一定要先保存,要不是瞬时对象 session.save(stu2); Set stuSet = new HashSet(); stuSet.add(stu1); stuSet.add(stu2); Classes c = new Classes(); c.setName("Java Class"); c.setStudents(stuSet); session.save(c); ta.commit(); }catch(Exception e){ e.printStackTrace(); if(ta != null){ ta.rollback(); } }finally{ //关闭session, user变为detached离线对象 HibernateUtil.closeSession(session); } }
Hibernate: insert into student (name) values (?)
Hibernate:insertintostudent(name)values(?)
Hibernate:insertintoclasses(name)values(?)
Hibernate:updatestudentsetclass_id=?whereid=?
Hibernate: update student set class_id=? where id=?注:表student 的字段class_id必须null(若为not null,就会报错)。多了2条update, 所以one-to-many保存时,不太好,不推荐。