如何在Hibernate中定义复合外键映射?
我有两个表:USERS和USERDILES如下:
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是一个复合主键,我希望用户详细信息中的相同字段作为外键。如何在休眠中实现这一点?
解决方案
我们需要将两个键都放在@Embeddable
中以分离复合键,然后使用@EmbeddedId
将其放入User
实体中,并使用Hibernate Relational Mapping
...
Composite Primary Key
有两个选项:
- 使用
@EmbeddedId
- 使用
@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
用户表:
用户明细表:
相关文章