Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createNativeQuery mapping to POJO (non-entity)

I have an easy problem at the first glance:

entityManager()
.createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla") 

And I want to write select result into POJO, like this:

public class AggregateStatsDto {

    private int total;

    private long totalSum;

    // getters, setters, cosntructors
}

What the best way to achieve this?

I can use JPA 2.1 and tried to use @SqlResultSetMapping in conjuction with @ConstructorResult:

@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
        @ConstructorResult(targetClass = AggregateStatsDto.class,
                columns = {
                        @ColumnResult(name = "total"),
                        @ColumnResult(name = "totalSum")
                })
})
public class AggregateStatsDto {

        private long total;

        private int totalSum;

        // getters, setters, cosntructors
    }

Query:

AggregateStatsDto result = (AggregateStatsDto) entityManager()
    .createNativeQuery("select count(*) as total, select sum(field) as total_sum ... blabla", "AggregateStatsResult")
    .getSingleResult();

But no luck. It seems that it wants @Entity anyway. But I want just a POJO.

org.hibernate.MappingException: Unknown SqlResultSetMapping [AggregateStatsResult]"

Thanks in advance!

like image 791
fasth Avatar asked Nov 09 '14 18:11

fasth


People also ask

How do I map native query results to pojo?

Solution: JPA supports @SqlResultSetMappings which you can use to map the query result to a POJO. The following code snippet shows an example of such a mapping. The @ConstructorResult annotation defines a constructor call of the BookValue class.

How do you map native query results to entities?

The easiest way to map a query result to an entity is to provide the entity class as a parameter to the createNativeQuery(String sqlString, Class resultClass) method of the EntityManager and use the default mapping.

What is createNativeQuery in JPA?

Create ad-hoc native queries Creating an ad-hoc native query is quite simple. The EntityManager interface provides the createNativeQuery method for it. It returns an implementation of the Query interface, which is the same that you get when you call the createQuery method to create a JPQL query.


1 Answers

Put your @SqlResultSetMapping annotation in a class which is an actual entity, not in the DTO Class. Your entity manager can not discover your mapping when you annotate a SqlResultSetMapping in a non-entity.

@SqlResultSetMapping(name = "AggregateStatsResult", classes = {
    @ConstructorResult(targetClass = AggregateStatsDto.class,
            columns = {
                    @ColumnResult(name = "total"),
                    @ColumnResult(name = "totalSum")
            })
})
@Entity
public class SomeOtherClassWhichIsAnEntity {
like image 184
jeff Avatar answered Oct 05 '22 14:10

jeff