一 环境:W7+Eclipse3.6+JDK1.6+MySQL
二 所用Hibernate版本:hibernate-distribution-3.6.0
三 具体代码
1 Annotations版本
主导对象
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity
public class A {
private int id;
private String name;
private B b;
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
@OneToOne
@PrimaryKeyJoinColumn
public B getB() {
return b;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setB(B b) {
this.b = b;
}
}
被参考对象
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity
public class B{
private int id;
private String name;
@Id
@GeneratedValue
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;
}
}
XML版本
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="org.hibernate.model.A">
<id name="id" column="id">
<!-- <generator class="native"/> -->
<generator class="foreign">
<param name="property">b</param>
</generator>
</id>
<property name="name"/>
<one-to-one name="b" constrained="true"></one-to-one>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="org.hibernate.model.B">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
SQL
create table A (
id integer not null auto_increment,
name varchar(255),
bId integer unique,
primary key (id)
)
create table B (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)
alter table A
add index FK418DB1FDB2 (id),
add constraint FK418DB1FDB2
foreign key (id)
references B (id)