saadoune
saadoune

Reputation: 419

Return types of JPQL queries

I actually need to query the database using JPQL. I don't find any way to return a List of List of Objects. In the following link http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-select it is possible to return List of Object[] but I don't see how to make it fit with the type I need to return which is a List of List Object. Thank you for your Help.

Upvotes: 2

Views: 1598

Answers (1)

Edd
Edd

Reputation: 2032

To create an object from a query first you have to create a class for the fields you want to get, for example:

package com.my.package;

public class MyObject {

    private String fieldOne;
    private String fieldTwo;

    public MyObject(String fieldOne, String fieldTwo) {
        this.fieldOne = fieldOne;
        this.fieldTwo = fieldTwo;
    }

    // Other methods...
}

Then your jpql query for these specific fields would look like:

SELECT new com.my.package.MyObject(t.fieldOne, t.fieldTwo) FROM MyTable t

You can use it in your repositories using the @Query annotation like this:

@Query("SELECT new com.my.package.MyObject(t.fieldOne, t.fieldTwo) FROM MyTable t")
List<MyObject> findMyObjects();

Or using the EntityManager:

EntityManager entityManager = ...;

entityManager
        .createQuery("SELECT new com.my.package.MyObject(t.fieldOne, t.fieldTwo) FROM MyTable t", MyObject.class)
        .getResultList();

Upvotes: 2

Related Questions