A good 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();

This gives an error " Cannot create TypedQuery for query with more than one return". I could get around this by leaving a 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 does not require uncontrolled code?

+5
source share
2 answers

A tuple is actually not more typical than an array, is it?

What you can do here is use a constructor expression. At the top of my head, it's 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 store the result, but this is usually pretty trivial.

+11
source

I don’t think so, except using the criteria API.

, , createQuery, , . , .

SuppressWarnings - , . , , - , , .

+4

All Articles