首页 > 代码库 > Hibernate-----一对一唯一外键关联映射(注解)

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;
    }
 }








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