使用JPA选择元组的好方法 [英] Nice way to select a tuple using JPA
问题描述
final List<Tuple> data =
em.createQuery("SELECT p.id AS i, p.membership AS m FROM Player p WHERE p.id IN :ids", Tuple.class)
.setParameter("ids", ids)
.getResultList();
这将显示错误"Cannot create TypedQuery for query with more than one return
".我可以通过省去类型参数(并使用Object []代替Tuple,稍后再发现)来解决此问题:
This gives the error "Cannot create TypedQuery for query with more than one return
". I could work around that by leaving out the type parameter (and using Object[] instead of Tuple, as I later found out):
@SuppressWarnings("unchecked")
final List<Object[]> data =
em.createQuery("SELECT p.id AS i, p.membership AS m FROM Player p WHERE p.id IN :ids")
.setParameter("ids", ids)
.getResultList();
但是有没有不需要未经检查的代码的解决方案?
But is there a solution that doesn't require unchecked code?
推荐答案
元组实际上不是比数组更类型安全的,不是吗?
A tuple isn't really any more typesafe than an array, is it?
您可以在这里使用构造函数表达式.在我的头顶上,就像这样:
What you could do here is use a constructor expression. Off the top of my head, this is something like:
class PlayerMembership {
public final int id;
public final MembershipType membership;
public PlayerMembership(int id, MembershipType membership) {
this.id = id;
this.membership = membership;
}
}
List<PlayerMembership> data =
em.createQuery("SELECT NEW nl.bart.PlayerMembership(p.id, p.membership) FROM Player p WHERE p.id IN :ids", PlayerMembership.class)
.setParameter("ids", ids)
.getResultList();
这需要您编写一个新类来保存结果,但这通常很简单.
This requires you to write a new class to hold the result, but this will typically be pretty trivial.
这篇关于使用JPA选择元组的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!