Hibernate学习笔记_08_一对一单向、双向主键关联

主键关联和外键关联类似,只需要将对应的注解稍作修改即可,主键关联用的很少。


1、写Husband.java类,并在其中添加对Wife的引用,同时注解。

package com.hibernate._0800_one2one_uni_pk;

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

@Entity
public class Husband {
	private Integer id;
	private String name;
	private Wife wife;	  //去参考wife的id,此时wife必须先id

	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	@OneToOne    //设置关联关系
	@PrimaryKeyJoinColumn(name="wifeId")            //@PrimaryKeyJoinColumn用主键来做连接,指定数据库中的名字,默认为wife_id
	public Wife getWife() {
		return wife;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	
}

@PrimaryKeyJoinColumn 设置用主键来做连接


2、写Wife.java类

package com.hibernate._0800_one2one_uni_pk;

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

@Entity
public class Wife {
	private Integer id;
	private String name;
	private Husband husband;
	
/** mappedBy="wife"中的这个wife是Husband中的wife属性,表示Husband起主导作用
	如果不加,在数据库中Wife表中会生成husband_id这个冗余字段*/
	
	@OneToOne(mappedBy="wife")      
        public Husband getHusband() {
		return husband;
	}
	@Id
        @PrimaryKeyJoinColumn(name="husbandId")         //加上这个注解就变成一对一双向主键关联
       public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setHusband(Husband husband) {
		this.husband = husband;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}	
	
}

设置mappedBy属性,mappedBy="wife"中的这个wife是Husband中的wife属性,表示Husband起主导作用如果不加,在数据库中Wife表中会生成husband_id这个冗余字段


                                                                                                                                                                                                                                         


3、XML中的配置。

单向主键关联时,

Husband.hbm.xml文件中配置如下:

<id name="id">
	<generator class="foreign">
		<param name="property">wife</param>   <!-- 这个值wife -->
	</generator>      <!--不写貌似也没关系,但最好还是class="" 值最好设为foreign-->
</id>		
	<property name="name" />
	<one-to-one name="wife" constrained="true"/>   <!-- 加上constrained="true"来设定外键约束 -->
Wife.hbm.xml 中的配置如下;

<id name="id">
      <generator class="native"></generator>
</id>		
<property name="name" />


双向主键关联时,

Husband.hbm.xml文件中配置如下:

<id name="id">
	<generator class="native"></generator>
</id>		
<property name="name" />
<one-to-one name="wife" property-ref="husband"/>
Wife.hbm.xml 中的配置如下;

<id name="id">
	<generator class="native"></generator>
</id>		
<property name="name" />
<one-to-one name="husband" constrained="true"/> 


你可能感兴趣的:(Hibernate学习笔记_08_一对一单向、双向主键关联)