15

我正在尝试使用 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 - 你能回答这个问题吗?

4

2 回答 2

8

对此的一种解决方案是避免使用“加入”功能,而是进行完全交叉连接:

EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<LoginNotification> query = cb.createQuery(LoginNotification.class);
Root<LoginNotification> notfRoot = query.from(LoginNotification.class);
Root<LoginEvent> eventRoot = query.from(LoginEvent.class);
...
query.where(cb.equals(notfRoot.get(Notification_.event), eventRoot.get(Event_.id)), ...(other criteria));

我会假设一个体面的查询优化器应该做这个简短的工作,但如果有人对这种方法的效率有任何见解,我会很想听到它!

于 2011-01-03T04:56:29.893 回答
0

我试过你的通用代码,@logan。

但我终于找到了最简单的方法是 let TimplementsSerializable

@Entity
public class IgsSubject extends BasicObject implements Serializable{

    private static final long serialVersionUID = -5387429446192609471L;
于 2015-12-14T15:09:57.923 回答