一对一单向外键关联通过XML方式来实现。譬如一个学生对应一个学生证,而一个学生证也只能对应一个学生,这样形成一对一的关联.
学生类:
public class Student {
private int id;
private String name;
private int age;
private String sex;
private boolean good;
学生证类
public class StuIdCard {
private int id;
private String num;
private Student student;
学生的配置文件student.hbm.xml
<hibernate-mapping>
<class name="com.bjsxt.hibernate.Student" dynamic-update="true">
<id name="id">
<generator class="native"></generator>
</id>
<property name="name"></property>
<property name="age" />
<property name="sex" />
<property name="good" type="yes_no"></property>
</class>
</hibernate-mapping>
学生证的配置文件:
<hibernate-mapping>
<class name="com.bjsxt.hibernate.StuIdCard">
<id name="id">
<generator class="native"></generator>
</id>
<property name="num"/>
//通过配置文件来设定一对一关系式是用many-to-one,表示多个学生证对应一个学生,然后设置unique之后表示一对一关联
<many-to-one name="student" column="studentId" unique="true"></many-to-one>
</class>
</hibernate-mapping>
hibernate的配置文件如下:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">bjsxt</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/>
<mapping resource="com/bjsxt/hibernate/StuIdCard.hbm.xml"/>
</session-factory>
</hibernate-configuration>