在本文(How to map multiple JPA entities to one database table with Hibernate)之后,我尝试使用@MappedSuperclass在两个实体之间共享同一个表,
所以我有3个类:
@MappedSuperclass
abstract class UserDao {
@Id
@Column(name = "username", nullable = false, unique = true)
var username: String? = null
@OneToMany(fetch = FetchType.EAGER)
var groups: Set<GroupDao>? = null
}然后:
@Entity(name = "basic_user_auth")
@Table(name = "users")
class BasicUserDao : UserDao() {
}和:
@Entity(name = "full_auth_user")
@Table(name = "users")
class FullUserDao : UserDao() {
@OneToOne
@PrimaryKeyJoinColumn
var profileJpa: ProfileDao? = null
}我尝试的是在不需要的时候节省一些加载用户配置文件的查询开销,但现在当我尝试运行应用程序时,我得到了以下错误:
could not execute statement; SQL [n/a]; constraint [full_auth_user_username" of relation "users_groups];不确定为什么Hibernate会创建这种关系,因为它们都共享同一个表。
发布于 2021-02-01 16:59:49
我建议您不要在实体级别上共享类型。当涉及多个这样的实体时,在刷新/同步方面,共享一对多关联可能不会像您预期的那样工作。我认为您应该尝试DTO方法。
我认为这是Blaze-Persistence Entity Views的一个完美用例。
我创建了这个库,以便在JPA模型和自定义接口或抽象类定义的模型之间轻松映射,就像Spring数据在类固醇上的投影一样。其思想是以您喜欢的方式定义目标结构(域模型),并通过JPQL表达式将属性(Getter)映射到实体模型。
使用Blaze-Persistence实体视图,您的用例的DTO模型可能如下所示:
@EntityView(User.class)
public interface BasicUserDao {
@IdMapping
String getUsername();
Set<GroupDao> getRoles();
@EntityView(Group.class)
interface GroupDao {
@IdMapping
Long getId();
String getName();
}
}
@EntityView(User.class)
public interface FullUserDao extends BasicUserDao {
@Mapping("profileJpa")
ProfileDao getProfile();
@EntityView(Profile.class)
interface ProfileDao {
@IdMapping
Long getId();
String getName();
}
}查询就是将实体视图应用于查询,最简单的就是通过id进行查询。
BasicUserDao a = entityViewManager.find(entityManager, BasicUserDao.class, id);
Spring数据集成允许您像使用Spring数据投影一样使用它:https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
@Repository
interface UserRepository {
List<BasicUserDao> findAll();
}最好的一点是,它只会获取实际需要的数据。
https://stackoverflow.com/questions/65985881
复制相似问题