我正在尝试使用 JPA 2.0 创建具有通用关系的多态实体。应该有两个表,一个事件表和一个通知表。在这些表中是相互关联的具体实体,如下所示:
Event <---------- Notification<X extends Event>
| |
LoginEvent <------ LoginNotification extends Notification<LoginEvent>
从逻辑上讲,这在休眠中应该是可能的,因为在 SQL 中是可能的:
+----------+ +----------+
| Event | | Notif |
+----------+ +----------+
| | | Id |
| Id | <- | Evt_id |
| Type | <- | Type |
| ... | | ... |
+----------+ +----------+
这就是我所拥有的:
@Entity
@Inheritance
public abstract class Event{
...
}
@Entity
public class LoginEvent extends Event{
...
}
@Entity
@Inheritance
public abstract class Notification<X extends Event>{
@ManyToOne(optional=false, targetEntity=Event.class)
@JoinColumn
private X event;
...
}
@Entity
public class LoginNotification extends Notification<LoginEvent>{
...
}
使用此代码,我可以持久化和获取任何事件、通知、登录事件或通知事件,但是当我尝试LoginNotification_.event
在我的 JPA 2.0 元模型查询中使用该关系时,它会失败。这个问题解释了类似的事情。
public static volatile SingularAttribute<NotificationEntity, EventEntity> event;
当我尝试在条件查询中进行联接时,出现错误:
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<LoginNotification> query = cb.createQuery(LoginNotification.class);
Root<LoginNotification> root = query.from(LoginNotification.class);
// This line complains: Type mismatch: cannot convert from
// Join<LoginNotification,Event> to Join<LoginNotification,LoginEvent>
Join<LoginNotification, LoginEvent> join =
root.join(LoginNotification_.event, JoinType.INNER);
我可以通过向元模型添加一个新的来解决此错误,SingularAttribute
但这LoginNotification_
在执行中失败:
public abstract class LoginNotification_ extends Notification_ {
// Adding this Removes Type mismatch error, but causes run-time error
public static volatile SingularAttribute<LoginNotification, LoginEvent> event;
...
}
根据一些帖子,通用关系不起作用(如何处理指向通用接口的指针的 JPA 注释),但通过使用@ManyToOne(optional=false, targetEntity=Event.class)
注释,我们可以让它们表现出来。不幸的是,泛型似乎破坏了 JPA 标准查询。
关于如何执行此查找有什么建议吗?我可以LoginNotification.getEvent()
在我的代码中使用,但我不能LoginNotification_.event
在我的 JPA 元模型连接中使用。使用泛型来实现这一点的替代方法是什么?
@Pascal Thivent - 你能回答这个问题吗?