Hibernate之one-to-one双向外键关联Annotation详解编程语言

Husband.java

package com.blog.ytso.com.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.blog.ytso.com.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)

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/14395.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论