一対一双方向外部キー連合プライマリキー(annotation方式)
3305 ワード
プライマリ・キー・クラス
オブジェクトのプライマリ・キーの設定
関連付けの設定
hibernate.hb.xml構成とテスト
参照
結果
package org.hibernate.tutorial.domain;
public class WifePK implements Serializable {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
オブジェクトのプライマリ・キーの設定
@Entity
@IdClass(WifePK.class)
public class Wife {
private int id;
private String name;
private String age;
@Id
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
@Id
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
関連付けの設定
@Entity
public class Husband {
private int id;
private String name;
private Wife wife;
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
@OneToOne
@JoinColumns(
{
@JoinColumn(name="wifeId",referencedColumnName="id"),
@JoinColumn(name="wifeName",referencedColumnName="name")
}
)
public Wife getWife() {
return wife;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}
hibernate.hb.xml構成とテスト
参照
public class OneToOneORMappingTest {
public static void main(String[] args) {
new SchemaExport(new AnnotationConfiguration().configure("/hibernate.cfg.xml")).create(true, false);
}
}
結果
alter table Husband
drop
foreign key FK_sdshifqwgidsm93jdh5kfl0e4
drop table if exists Husband
drop table if exists Wife
create table Husband (
id integer not null auto_increment,
name varchar(255),
wifeId integer,
wifeName varchar(255),
primary key (id)
)
create table Wife (
id integer not null,
name varchar(255) not null,
age varchar(255),
primary key (id, name)
)
alter table Husband
add index FK_sdshifqwgidsm93jdh5kfl0e4 (wifeId, wifeName),
add constraint FK_sdshifqwgidsm93jdh5kfl0e4
foreign key (wifeId, wifeName)
references Wife (id, name)