Hibernate 一对一主键 单向关联
使用范围:1个表的主键,与另一个表的主键 1:1 对应。
1-1的关联可以基于主键关联,但基于主键关联的持久化类不能拥有自己的主键生成策略,它的主键由关联类负责生成。另外,另外,增加one-to-one元素来关联属性,必须为one-to-one元素增加constrained="true"属性,表明该类主键由关联类生成。
一、模型介绍
一个人(Person)对应一个身份证(IDCard)。
二、实体(省略getter、setter方法)
public class Person {
private int personid;
private String name;
private int age;
private IDCard iDCardPk; //作为外键关联
}
public class IDCard{
private int idCardid;
private String idCardName;
}
三、表模型
mysql> desc idcard;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| idcardid | int(11) | NO | PRI | NULL | auto_increment |
| idcardname | varchar(255) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
mysql> desc person;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| personid | int(11) | NO | PRI | | |
| name | varchar(255) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
四.映射方法:在Person中配置id生成策略为:
<hibernate-mapping>
<class name="com.lavasoft.Person" table="PERSON">
<id name="personid" column="presonid">
<!--基于主键关联时,主键生成策略是foreign,表明根据关联类生成主键-->
<generator constrained="true"/>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.lavasoft.IDCard" table="idcard">
<id name="idCardid">
<generator class="identity"/>
</id>
<property name="idCardName"/>
</class>
</hibernate-mapping>
六、测试方法
public class Test_11pk {
public static void main(String[] args){
Person p1=new Person();
p1.setAge(21);
p1.setName("p1");
IDCard card1 = new IDCard();
card1.setIdCardName("kexcking");
p1.setIdCardpk(card1);
Session session= HibernateUtil.getCurrentSession();
Transaction tx=session.beginTransaction();
session.save(card1);
session.save(p1);
tx.commit();
HibernateUtil.closeSession();
}
}