hibernate关联映射(注解) —— 基于外键的双向一对一关联映射(@OneToOne)

hibernate基于注解的一对多关联使用@OneToOne注解。
注意:需要引入的为: javax.persistence.OneToOne


维护端(有外键方):

//不要忘记加 unique = true,否则和多对一一样!
@OneToOne(fetch = FetchType.EAGER)//设置加载
@Cascade(CascadeType.ALL)//设置级联操作
@JoinColumn(name = "外键名",unique = true)

被维护端(无外键方):

@OneToOne(mappedBy="外键对应的属性名") 
@Cascade(CascadeType.ALL)

假设有两个类:User(用户)与IdCard(身份证),一个用户对应一个身份证。

User 类 如下

import javax.persistence.Basic;
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;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity 
@Table(name = "user")
public class User {
    private int userId;
    private String username;
    private IdCard idCard;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userId")
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    //不要忘记加 unique = true,否则和多对一一样!
    @OneToOne(fetch = FetchType.EAGER)//设置加载
    @Cascade(CascadeType.ALL)//设置级联操作
    @JoinColumn(name = "idCardId",unique = true)
    public IdCard getIdCard() {
        return idCard;
    }

    public void setIdCard(IdCard idCard) {
        this.idCard = idCard;
    }

}

IdCard 类 如下

import javax.persistence.Basic;
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;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity
@Table(name = "idCard")
public class IdCard {
    private int Id;
    private String idno;
    private User user;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "idCardId", nullable = false)
    public int getId() {
        return Id;
    }
    public void setId(int id) {
        Id = id;
    }

    @Basic
    @Column(name = "idno", nullable = false)
    public String getIdno() {
        return idno;
    }
    public void setIdno(String idno) {
        this.idno = idno;
    }

    @OneToOne(mappedBy="idCard") 
    @Cascade(CascadeType.ALL)
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }


}

hibernate自动建表操作结果 :
hibernate关联映射(注解) —— 基于外键的双向一对一关联映射(@OneToOne)_第1张图片

你可能感兴趣的:(hibernate)