我试图用 JPA 实体实现 Generation Gap Pattern。这是我们选择的解决方案( <-- 是继承)
BaseEntity <-- EntityGenerated <-- Entity
Run Code Online (Sandbox Code Playgroud)
EntityGenerated 类型是抽象的并使用@MappedSuperclass 映射,所有字段都使用正确的映射注释生成,关系指向具体的子类,而不是 Generated 。
Entity 是一个具体的类型,只有当类不存在时才生成,最初只有用@Entity 注释的类声明。其他映射属性(如@Table 等)位于生成的 orm.xml 中。
现在,当我们生成 jpa 静态元模型(使用 hibernate 或 openjpa 元模型生成器)时,生成的类如下所示:
public class BaseEntity_ {
public static volatile SingularAttribute<PersistentDomainObject,Long> id;
public static volatile SingularAttribute<PersistentDomainObject,Long> timeStamp;
}
public class UserGenerated_ extends BaseEntity_ {
public static volatile SetAttribute<UserGenerated,Group> groups;
}
public class User_ extends UserGenerated_ {
}
Run Code Online (Sandbox Code Playgroud)
如果我想在 jpa 条件查询中使用 User_,我将执行以下操作:
CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);
Root<User> root = query.from(User.class);
query.where(root.get(User_.groups).in(paramGroups));
Run Code Online (Sandbox Code Playgroud)
但它不会编译.... User_.groups …