【hibernate框架】一对一单向主键关联(Annotation实现)

单项主键关联指的是:husband和wife之间有关联关联的。但是是用主键做关联的,说白了就是husband的id会参考wife的id(husband的id是1,n那么它所对应的wife的id也是1)。

Husband.java:
package cn.edu.hpu.one2one;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;


@Entity
public class Husband {
	private int id;
	private String name;
	private Wife wife;


	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	@OneToOne
	//@JoinColumn(name="wifeid")
	@PrimaryKeyJoinColumn //用主键做连接的一种东西
	public Wife getWife() {
		return wife;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
	
}




wife.java:
package cn.edu.hpu.one2one;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;


@Entity
public class Wife {
	private int id;
	private String name;
	private Husband husband;


	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}


	@OneToOne(mappedBy="wife")
	public Husband getHusband() {
		return husband;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}



生成的建表语句:
 create table Husband (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )


    create table Wife (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )


    alter table Husband 
        add index FKAEEA401BF5211E1C (id), 
        add constraint FKAEEA401BF5211E1C 
        foreign key (id) 
        references Wife (id)
schema export complete
可以看见Wife和Husband表里面没有外键的字段,但是两个主键之间会设关联。
(看数据库的图形化界面,你也会看到husband的id字段上有小钥匙的图标,这就是一个主键关联)

你可能感兴趣的:(java,框架,Hibernate,ejb,一对一单向主键关联)