Hibernate一对一主键单向关联 |
|
1-1的关联可以基于主键关联,但基于主键关联的持久化类不能拥有自己的主键生成策略,它的主键由关联类负责生成。另外,另外,增加one-to-one元素来关联属性,必须为one-to-one元素增加constrained="true"属性,表明该类主键由关联类生成。 |
|
一、模型介绍 |
|
一个人(Person)对应一个地址(Address)。 |
|
二、实体(省略getter、setter方法) |
|
public class Person11pk { |
private int personid; |
private String name; |
private int age; |
private Address11pk address11pk; |
|
public class Address11pk { |
private int addressid; |
private String addressdetail; |
|
三、表模型 |
|
mysql> desc address_11pk; |
+---------------+--------------+------+-----+---------+----------------+ |
| Field | Type | Null | Key | Default | Extra | |
+---------------+--------------+------+-----+---------+----------------+ |
| addressid | int(11) | NO | PRI | NULL | auto_increment | |
| addressdetail | varchar(255) | YES | | NULL | | |
+---------------+--------------+------+-----+---------+----------------+ |
|
mysql> desc person_11pk; |
+----------+--------------+------+-----+---------+-------+ |
| Field | Type | Null | Key | Default | Extra | |
+----------+--------------+------+-----+---------+-------+ |
| personid | int(11) | NO | PRI | | | |
| name | varchar(255) | YES | | NULL | | |
| age | int(11) | YES | | NULL | | |
+----------+--------------+------+-----+---------+-------+ |
|
四、生成的SQL脚本 |
|
/* Formatted on 2007/08/22 14:40 (QP5 v5.50) */ |
CREATE TABLE `address_11pk` ( |
`addressid` int(11) NOT NULL auto_increment, |
`addressdetail` varchar(255) default NULL, |
PRIMARY KEY (`addressid`) |
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gbk; |
|
|
/* Formatted on 2007/08/22 14:41 (QP5 v5.50) */ |
CREATE TABLE `person_11pk` ( |
`presonid` int(11) NOT NULL, |
`name` varchar(255) default NULL, |
`age` int(11) default NULL, |
PRIMARY KEY (`presonid`), |
KEY `FK68A882C591BB393E` (`presonid`), |
CONSTRAINT `FK68A882C591BB393E` FOREIGN KEY (`presonid`) REFERENCES `address_11pk` (`addressid`) |
) ENGINE=InnoDB DEFAULT CHARSET=gbk; |
|
|
五、映射方法:在Person中配置id生成策略为: |
OneToOnePKPerson.hbm.xml
|
OneToOnePKAddress.hbm.xml
六、测试方法
|