Hibernate:一对一单向外键关联

一 环境:W7+Eclipse3.6+JDK1.6+MySQL
二 所用Hibernate版本:hibernate-distribution-3.6.0.Final
三 具体代码
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
	@JoinColumn(name="bid")
        //指定关联列名
	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"/>
        </id>
        <property name="name"/>
	    <many-to-one name="b" column="bid"  unique="true"/>
    </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 FK418DB36D94 (bId), 
        add constraint FK418DB36D94 
        foreign key (bId) 
        references B (id)

你可能感兴趣的:(mysql,Hibernate,xml)