Hibernate之one-to-one双向外键关联Annotation

Husband.java

package com.itmyhome.model;

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

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

	/*
	 * Id生成策略 mysql默认是auto_crement
	 */
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	/*
	 * OneToOne
	 * JoinColumn用来指定生成的外键名字 
	 */
	@OneToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="wifeId")
	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 com.itmyhome.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
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;
	}

	/*
	 * 凡是双向必设mappedBy
	 * 如果不设mappedBy 双方都会加外键约束 
	 */
	@OneToOne(mappedBy="wife")
	@JoinColumn(name="husbandId")
	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;
	}

}


hibernate生成的sql如下:

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


 

create table Wife (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )
alter table Husband 
        add index FKAEEA401B78A8164D (wifeId), 
        add constraint FKAEEA401B78A8164D 
        foreign key (wifeId) 
        references Wife (id)


 

你可能感兴趣的:(annotation)