什么叫做单向?
就是在entity中体现为两个持久化对象中其中一个对象包含另一个对象的对象或者对象的集合.
什么叫做双向?
两个持久化对象相互关联,entity中都有对方的集合集合或者对象;
在hbm.xml中主要代码为
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.happy.entity"> <class name="Dept" table="Y2162Dept"> <id name="deptNo" column="deptNo"> <generator class="native"></generator> </id> <property name="deptName" type="string" column="deptName"/> <!-- 一对多 关联关系 --> <set name="emps" cascade="save-update,delete" inverse="true"> <key column="deptNo"></key> <one-to-many class="Emp"/> </set> </class> </hibernate-mapping>
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.happy.entity"> <class name="Emp" table="Y2162Emp"> <id name="empNo" column="empNo"> <generator class="native"></generator> </id> <property name="empName" type="string" column="empName"/> <!-- 单向的 多对一 --> <many-to-one name="dept" class="Dept" column="deptNo"></many-to-one> </class> </hibernate-mapping>
test代码块
@Test public void addTest(){ //创建员工对象 Emp emp=new Emp(); emp.setEmpname("未知"); //创建工程对象 Project pro=new Project(); pro.setPname("花园"); //将员工对象添加到工程 反之 同理 pro.getEmps().add(emp); emp.getPros().add(pro); //保存 session.save(pro); session.save(emp); }