首页 > 代码库 > Hibernate-----一对一共享主键关联映射(注解)

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 = http://www.mamicode.com/"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;
    }
}
 






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