onetoone:单向
1,主键关联:
在关联放使用@OneToOne
sql语句:(类代码见同前面的代码)
Java代码
create table A (id integer not null auto_increment, aname varchar(255), b_id integer, primary key (id))
create table B (id integer not null auto_increment, bname varchar(255), primary key (id))
alter table A add index FK41FCD34905 (b_id), add constraint FK41FCD34905 foreign key (b_id) references B (id)
可以使用@PrimaryKeyJoinColumn进行关联
2 双向:
在关联方使用
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="b")
被关联方使用
@OneToOne(mappedBy="b")
最终sql:
Java代码 create table A (id integer not null auto_increment, aname varchar(255), b integer, primary key (id))
create table B (id integer not null auto_increment, bname varchar(255), primary key (id))
alter table A add index FK41FCA54B4F (b), add constraint FK41FCA54B4F foreign key (b) references B (id)
如果不写
@OneToOne(mappedBy="b")则会在被关联放也生成一个字段
最终代码:
Java代码
create table A (id integer not null auto_increment, aname varchar(255), i_id integer, primary key (id))
create table B (id integer not null auto_increment, bname varchar(255), a_id integer, primary key (id))
alter table A add index FK41FCD6779E (i_id), add constraint FK41FCD6779E foreign key (i_id) references B (id)
alter table B add index FK42FCD2D4A5 (a_id), add constraint FK42FCD2D4A5 foreign key (a_id) references A (id)
如果没有写@JoinColumn(name="b")则默认是关联属性名+下划线+id
最终sql:
Java代码
create table A (id integer not null auto_increment, aname varchar(255), b_id integer, primary key (id))
create table B (id integer not null auto_increment, bname varchar(255), primary key (id))
alter table A add index FK41FCD34905 (b_id), add constraint FK41FCD34905 foreign key (b_id) references B (id)
可以使用@JoinColumn(referencedColumnName="bname")让主关联方不关联被关联放的主键
最终sql
Java代码
create table A (id integer not null auto_increment, aname varchar(255), b_bname varchar(255), primary key (id))
create table B (id integer not null auto_increment, bname varchar(255), primary key (id), unique (bname))
alter table A add index FK41E47CD6BD (b_bname), add constraint FK41E47CD6BD foreign key (b_bname) references B (bname)