hibernate - Table-per-concrete-class 继承映射和 OneToMany
问题描述
我的应用程序需要支持使用来自另一个系统的注册用户。这个映射很好,我可以从两个表中加载和查询:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
abstract class User {
private String id; // "username"
}
@Entity
@Table("MY_APP_USER")
abstract class MyAppUser extends User {
// other properties
}
@Entity
@Table("OTHER_APP_USER")
abstract class OtherAppUser extends User {
// other properties
}
问题是在其他实体中的映射,有两种情况,第一种情况:
@Entity
@Table("ERROR")
class Error {
// other properties
@JoinColumn(name = "my_app_user")
@OneToOne(fetch = FetchType.EAGER)
private MyAppUser myAppUser;
@JoinColumn(name = "other_app_user")
@OneToOne(fetch = FetchType.EAGER)
private OtherAppUser otherAppUser;
public User getUser() {
return myAppUser != null ? myAppUser : otherAppUser;
}
public void setUser(User user) {
if (user instanceof MyAppUser)
this.myAppUser = (MyAppUser) user;
else if (user instanceof OtherAppUser)
this.otherAppUser = (OtherAppUser) user;
}
}
这似乎有效,但这是正确的方法吗?
第二种情况,这对我来说似乎很棘手,即使在阅读了几次文档之后:
@Entity
@Table("REPORT")
class Report {
// other properties
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "REPORT_USER",
joinColumns = @JoinColumn(name = "report_id"),
inverseJoinColumns = @JoinColumn(name = "????????"))
private Set<User> setUsers;
}
我不能使用触发器来确保数据完整性,所以我在每个需要用户的地方添加两列:my_app_user 和 other_app_user。所以,我需要在“inverseJoinColumns”中指定两列,我该怎么做?我像在 Erro 类中那样映射它两次,并在 gette/setter 中做解决方法?还有另一种方法可以做到这一点吗?
解决方案
我也遇到了 ManyToMany 问题,我留下了原始帖子中的代码,而不是使用 @JoinTable,我为 @JoinTable 创建了实体,并在映射中使用了该实体。
推荐阅读
- pygame - 为什么我无法使用 Anaconda Navigator 安装/搜索 pygame 包?
- laravel - 在 Eloquent 中保存 HasMany 和 asscoiate BelongsTo
- javascript - puppeteer 计算下拉列表中的项目数
- java - 如何抑制声纳安全热点的警告?
- java - Java Socket 编程中的 java.nio.channels.ClosedChannelException
- hash - 如何在 SAS 中使用哈希对象进行模糊字符合并?
- clang - clang matcher:获取 VarDecl 的左侧
- web3 - 从钱包中获取煎饼余额
- python - 如何找到连续函数的第二个峰值?
- javascript - 如何使用 JavaScript 覆盖表单验证