如何在休眠中定义复合外键映射?

How to define composite foreign key mapping in hibernate?

我有两个表:users 和 userdetails 如下:

package com.example.easynotes.model;

import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "users")
@IdClass(UserID.class)
public class User implements Serializable {

    @Id
    int id;

    @Id
    String name;

    String department;

    //getters and setters

}

用户详细信息 类 将是这样的:

public class UserDetails implements Serializable{

int id;

String name;

String address;

String otherFields;

//getters and setters

}

users 中的 id 和 name 是复合主键,我希望 userdetails 中的相同字段成为外键。我怎样才能在休眠中实现这一目标?

我们需要将两个键都放在 @Embeddable 中以分离复合键,然后使用 @EmbeddedId 将其放在 User 实体中,并使用 Hibernate Relational Mapping 映射两个主键。 ..

Composite Primary Key有两个选项:

  1. 使用@EmbeddedId
  2. 使用@IdClass()

下面是示例:

------------------------------------ 使用 EmbeddedId --- ------------------------------

复合主键:

@Embeddable
public class UserIdName implements Serializable {
    int id;
    String name;
    
    // getter and setter
}

用户:

@Entity
@Table(name = "users")
public class USER{
    @EmbeddedId
    private UserIdName id;

    String department;
    
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private Set<Userdetail> userdetail;

    // getter and setter
}

用户详细信息:

@Entity
@Table(name = "Userdetail")
public class Userdetail {

    @Id
    private int detail_id;

    @ManyToOne
    @JoinColumns({ @JoinColumn(name = "id", referencedColumnName = "id"),
            @JoinColumn(name = "name", referencedColumnName = "name") })
    private USER user;

    String address;

    String otherFields;

    // getter setter
}

------------------------------------ 使用 IdClass --- ------------------------------

复合主键:

public class UserIdName implements Serializable {
    int id;
    String name;
    
    // getter and setter
}

用户:

@Entity
@Table(name = "users")
@IdClass(UserIdName.class)
public class USER{
    @Id
    int id;

    @Id
    String name;

    String department;
    
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private Set<Userdetail> userdetail;

    // getter and setter
}

用户详细信息:

@Entity
@Table(name = "Userdetail")
public class Userdetail {

    @Id
    private int detail_id;

    @ManyToOne
    @JoinColumns({ @JoinColumn(name = "id", referencedColumnName = "id"),
            @JoinColumn(name = "name", referencedColumnName = "name") })
    private USER user;

    String address;

    String otherFields;

    // getter setter
}

-> 如果你想手动插入两个外键尝试下面的代码

将此代码放入 UserDetails

@ManyToOne
@JoinColumn(name = "id", referencedColumnName = "id", insertable = false, updatable = false)
@JoinColumn(name = "name", referencedColumnName = "name", insertable = false, updatable = false)
private USER user;

@Column(name="id")
private int id;

@Column(name="name")
private String name

// don't forget to put getter setter

用户Table:

用户详细信息Table: