本文介绍了如何在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
用户表:
用户明细表:
这篇关于如何在Hibernate中定义复合外键映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!