注解:【基于外键的】Hibernate双向1->1关联

时间:2022-07-25 15:09:48

Person与Address关联:双向1->1,【基于外键的】。

  #主表不应该控制关联关系。(否则会导致生成额外的update语句,从而导致性能下降),

  #因此主表对应的实体中使用@OneToOne注解时,应该增加mappedBy属性。

Person.java

package org.crazyit.app.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "Person_inf")
public class Person {

@Column(name = "person_id")
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

private String name;

private Integer age;

// 双向1->1:对关联关系
// 定义该Person实体所有关联的Address
@OneToOne(targetEntity = Address.class, mappedBy = "person")
private Address address;

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}

Address.java

package org.crazyit.app.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "Address_inf")
public class Address {

@Id
@Column(name = "address_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

// 定义该Address实体关联的person实体
@OneToOne(targetEntity = Person.class)
// 用于映射person_id外键列,参照person_inf表的person_id列
// 指定unique=true,表名是1-1关联
@JoinColumn(name = "person_id", //
referencedColumnName = "person_id", //
unique = true) // 唯一性约束(unique)
private Person person;

// 地址详细
private String addressDetail;

// 无参构造方法
public Address() {
}

// 初始化全部成员变量
public Address(String addressDetail) {
this.addressDetail = addressDetail;
}

public Integer getId() {
return id;
}

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

public String getAddressDetail() {
return addressDetail;
}

public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}

public Person getPerson() {
return person;
}

public void setPerson(Person person) {
this.person = person;
}

}

#数据模型

注解:【基于外键的】Hibernate双向1->1关联