How to use @ConstructorResult annotation

Silence picture Silence · Mar 26, 2014 · Viewed 9.2k times · Source

I have some native query and want to map the result of query execution into List of NON-Entity POJO classes:

@SqlResultSetMapping(
    name = "SomeMapping",
    classes = {
        @ConstructorResult(targetClass = SomeClass.class,
            columns = {
                @ColumnResult(name = "id", type = Integer.class),
                @ColumnResult(name = "NAME", type = String.class),
                @ColumnResult(name = "DATE_BEGIN", type = java.util.Date.class)
            }
        )
    }
)

public class SomeClass{
    private Integer id;
    private String name;
    private java.util.Date begDate;
    private java.util.Date endDate;

    public SomeClass(Integer id, String name, Date begDate){
        this.id = id;
        this.name = name;
        this.begDate = begDate;
    }

    //Getters & Setters ...
}

And generally how i want to retrieve result of query execution:

String query = "SELECT " +
"A.id AS 'id', " +
"A.name AS 'NAME', " +
"A.begDate AS 'DATE_BEGIN' " + 
"FROM " +
"SomeTable A " +
"WHERE A.endDate < '2014-01-01'";

List<SomeClass> result = em.createNativeQuery(query, "SomeMapping").getResultList();

But i always get the List of Object. How to retrieve list of my POJO-s?

Answer

Andrei I picture Andrei I · Mar 26, 2014

Try moving the @SqlResultSetMapping entity on a Entity.