Hibernate:一対一のプライマリ・キー関連付け


環境:W 7+Eclipse 3.6+JDK1.6+MySQL
使用する2つの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)