**domain文件:**Studcourse.java
public class Studcourse { private BigDecimal stucourseid; private Student student; private Course course; private BigDecimal grade; }**配置文件:**Studcourse.hbm.xml
<many-to-one name="student" class="com.test.domain.Student" fetch="select"> <column name="SID" precision="22" scale="0" /> </many-to-one>**domain文件:**Student.java
public class Student implements java.io.Serializable { private BigDecimal sid; private String sname; private Set studcourses = new HashSet(0); }**配置文件:**Student.hbm.xml
<set name="studcourses" inverse="true"> <key> <column name="SID" precision="22" scale="0" /> </key> <one-to-many class="com.test.domain.Studcourse" /> </set>有两种方式:基于主键的一对一;基于外键的一对一。
**domain文件:**Person.java和IdCard.java
class Person{ private Integer id; private String name; private IdCard idCard; } class IdCard { private Integer id; private Date validateDte; private Person person; }配置文件: Person.hbm.xml
<one-to-one name="idCard" class="com.test.domain.IdCard"></one-to-one>IdCard.hbm.xml
<id name="id" type="java.lang.Integer"> <generator class="foreign"> <param name="property">person</param> </generator> </id> <one-to-one name="person" class="com.test.domain.Person" constrained="true"></one-to-one>**domain文件:**Person.java和IdCard.java
class Person{ private Integer id; private String name; private IdCard idCard; } class IdCard { private Integer id; private Date validateDte; private Person person; }配置文件: Person.hbm.xml
<one-to-one name="idCard" class="com.test.domain.IdCard"></one-to-one>IdCard.hbm.xml
<id name="id" type="java.lang.Integer"> <generator class="assigned" /> </id> // one-to-one实际上是many-to-one的一个特例 <many-to-one name="person" unique="true" />在操作和性能方面都不太理想,所以多对多的映射使用较少,实际使用中最好转换成一对多的对象模型;Hibernate会为我们创建中间关联表,转换成两个一对多。 domain文件:
public class Student implements java.io.Serializable { private BigDecimal sid; private String sname; private Set studcourses = new HashSet(0); } public class Course implements java.io.Serializable { private BigDecimal cid; private String cname; private Short ccredit; private Set studcourses = new HashSet(0); } public class Studcourse { private BigDecimal stucourseid; private Student student; private Course course; private BigDecimal grade; }配置文件: Student.hbm.xml 和 Course.hbm.xml
<set name="studcourses" inverse="true"> <key> <column name="S_ID" precision="22" scale="0" /> </key> <one-to-many class="com.test.domain.Studcourse" /> </set>Studcourse.hbm.xml
<many-to-one name="student" class="com.test.domain.Student" fetch="select"> <column name="S_ID" precision="22" scale="0" /> </many-to-one> <many-to-one name="course" class="com.test.domain.Course" fetch="select"> <column name="C_ID" precision="22" scale="0" /> </many-to-one>