[ref]http://xdoclet.sourceforge.net/xdoclet/tags/hibernate-tags.html http://www.hibernate.org/5.html
可用两种方法实现:
1. 主键关联
[主]: one-to-one
[从]: one-to-one constrained="true" name="@PP"
主键ID: generator-class="foreign" generator-param name="property" value="@PP"
2. 惟一外键关联
[主]: many-to-one unique="true" name="@P1"
[从]: one-to-one property-ref="@P1" (不需双向可省略该属性)
1. Station 1--1 StationDetail Station.id作为StationDetail的外键,存储为StationDetail.id.
Station (必须要有getDetail属性)
/**
* 修改StationDetail的id生成策略为foreign
* @hibernate.one-to-one cascade="all"
*/
public StationDetail getDetail() {
return detail;
}
StationDetail (必须要有getStation属性)
/**
* @hibernate property="id"
* @hibernate.id
* column="id"
* unsaved-value="-1"
* generator-class="foreign"
* @hibernate.generator-param name="property" value="station" station为指向外键的属性
*/
public Long getId() {
return id;
}
/**
* constrained="true" 表示使用该属性为主键
* @hibernate.one-to-one constrained="true" name="station"
* @return
*/
public Station getStation() {
return station;
}
产生SQL
create table t_station_detail (
id bigint not null,
address text,
email varchar(255),
fax varchar(255),
introduce text,
tel varchar(255),
primary key (id)
)
create table t_station (
id bigint not null auto_increment,
code varchar(10),
name varchar(255),
primary key (id)
)
alter table t_station_detail add index FKEADD08E7D1B (id), add constraint FKEADD08E7D1B foreign key (id) references t_station (id)
2. Station 1--1 StationDetail Station.station_detail存储为StationDetail.id
Station
/**
* 修改StationDetail的id生成策略为foreign
* @hibernate.many-to-one name="detail" column="station_detail" cascade="all" unique="true"
*/
public StationDetail getDetail() {
return detail;
}
StationDetail
id生成用native, 如不需要双向关联,下面可以不需要.
/**
* constrained="true" 表示使用该属性为主键
* @hibernate.one-to-one constrained="false" property-ref="detail"
* @return
*/
public Station getStation() {
return station;
}
产生SQL
create table t_station_detail (
id bigint not null auto_increment,
address text,
email varchar(255),
fax varchar(255),
introduce text,
tel varchar(255),
primary key (id)
)
create table t_station (
id bigint not null auto_increment,
code varchar(10),
station_detail bigint unique,
name varchar(255),
primary key (id)
)
alter table t_station add index FK4A7DF4695C5811BC (station_detail), add constraint FK4A7DF4695C5811BC foreign key (station_detail) references t_station_detail (id)