1

I have a named query on an entity that does not get the full table (*), but only 2 columns of it. How do I implement this named query and what is the return type of the List?

@NamedQueries({
        @NamedQuery(name="Text.testQuery", query = "SELECT DISTINCT t.col1, t.col2 FROM TextEntity t WHERE t.col1 = :type AND t.col2 LIKE :searchString")
})
@Entity
@Table(name = "TEXT")
public class TextEntity implements Serializable

    @Id
    @Column(length = 36)
    private String id;
    @Column(length = 16)
    private String col1 = null;
    @Column(length = 3)
    private String col2 = null;
    @Column(length = 2)
    private String col3 = null;
    @Column(length = 255)
    private String col4 = null;

and

public List<TextEntity> findErpIdByTypeAndSearchString(IEntity.Type type, String searchString, int maxResults) {
        Query query = em.createNamedQuery("Text.testQuery");
        query.setParameter("type", type);
        query.setParameter("searchString", "%" + searchString + "%");
        query.setMaxResults(maxResults);

        return query.getResultList();
    }

This returns an error:

Caused by: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.namespace.text.TextEntity

How would I do this when I don't get the whole table from the named query statement, but only two String columns?

luuksen
  • 1,357
  • 2
  • 12
  • 38
  • 2
    It is `List` as indicated by the exception message. – Tiny Nov 14 '14 at 13:33
  • Thanks for your answers. The object array hint was quite helpful, I can't believe I just skipped that and didn't think about it. I can now access the 2 columns via the list of those Object arrays. I thought there might be a more handy/safe solution though. – luuksen Nov 14 '14 at 13:43
  • 2
    You can also, if necessary, specify [a constructor query](http://www.ibm.com/developerworks/library/j-typesafejpa/#listing17) with a class which is mapped to the result list or a `Tuple` query. That example is about the JPA criteria API but the same thing is applicable to JPQL too, [for example](http://stackoverflow.com/a/12286281/1391249). – Tiny Nov 14 '14 at 13:55

0 Answers0