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

Husband.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 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 
	@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; 
 
@Entity 
public class Wife { 
	private int id; 
	private String name; 
	 
	@Id 
	@GeneratedValue 
	public int getId() { 
		return id; 
	} 
	public void setId(int id) { 
		this.id = id; 
	} 
	public String getName() { 
		return name; 
	} 
	public void setName(String name) { 
		this.name = name; 
	} 
	 
} 

hibernate为我们生成的表结构为:

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)

 

 

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

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

相关推荐

发表回复

登录后才能评论