Hibernate-----一对一共享主键关联映射(注解)

One(‘多’)

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
 @Entity
public class Wife {
    private int id;
    private String name;
 
    private Husband husband;
 
    /**
     * wife的ID是根据husband的ID来赋值的,需设置ID生成器的策略为foreign
     *
     * 参数中指定wife的ID是使用husband对象中的ID
     */
    @Id
    @GenericGenerator(name = "pkGenerator",
strategy = "foreign",
parameters = { @Parameter(name = "property", value = "husband") })
    @GeneratedValue(generator = "pkGenerator")
    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;
    }
 
    public void setHusband(Husband husband) {
       this.husband = husband;
    }
 
    @OneToOne(cascade = CascadeType.ALL)
    public Husband getHusband() {
       return husband;
    }
}
 

One(‘一’)

import javax.persistence.CascadeType;
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 int id;
    private String name;
    private Wife wife;
 
    @Id
    @GeneratedValue
    public int getId() {
       return id;
    }
 
    public String getName() {
       return name;
    }
 
    // 该注解只能写在主(生成ID)的一端
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    public Wife getWife() {
       return wife;
    }
 
    public void setId(int id) {
       this.id = id;
    }
 
    public void setName(String name) {
       this.name = name;
    }
 
    public void setWife(Wife wife) {
       this.wife = wife;
    }
}
 






郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。