Hibernate-----一对一唯一外键关联映射(注解)

双向关联映射:

One(‘Many’)

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
@Entity
public class Person implements java.io.Serializable {
    private Integer id;
    private String name;
 
    private IdCard idCard;
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
       return id;
    }
 
    public void setId(Integer id) {
       this.id = id;
    }
 
    @Column(name = "person_name")
    public String getName() {
       return name;
    }
 
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "idCard_id")
    public void setName(String name) {
        this.name = name;
    }
 
    public IdCard getIdCard() {
       return idCard;
    }
 
    public void setIdCard(IdCard idCard) {
       this.idCard = idCard;
    }
}

One(‘One’)

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.hibernate.annotations.GenericGenerator;
@Entity
public class IdCard implements java.io.Serializable {
    private Integer id;
    private String name;
 
    private Person person;
 
    @Id
    @GeneratedValue(generator = "TeacherGenerator")
    @GenericGenerator(name = "TeacherGenerator", strategy = "native")
    public Integer getId() {
       return id;
    }
 
    public void setId(Integer id) {
       this.id = id;
    }
 
    @Column(name = "name", nullable = false, length = 32)
    public String getName() {
       return name;
    }
 
    public void setName(String name) {
       this.name = name;
    }
 
    @OneToOne(mappedBy = "idCard")
    public Person getPerson() {
       return person;
    }
 
    public void setPerson(Person person) {
       this.person = person;
    }
 }








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