JPA Join Query(native query) custom dto

前端 未结 2 550
我寻月下人不归
我寻月下人不归 2021-01-27 07:10

Hi I am trying to join 3 table and fetch the collective result i.e dto using following query

SELECT f.id, u.email,
count(distinct l.id) as likes_count,
count(dis         


        
2条回答
  •  难免孤独
    2021-01-27 08:02

    You cannot use constructor expression (NEW operator) with Native Queries.

    You could use JPA constructor result. This looks like:

    Query q = em.createNativeQuery(
        "SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
        "FROM Customer c " +
        "JOIN Orders o ON o.cid = c.id " +
        "GROUP BY c.id, c.name",
        "CustomerDetailsResult");
    
    @SqlResultSetMapping(name="CustomerDetailsResult",
        classes={
            @ConstructorResult(targetClass=com.acme.CustomerDetails.class,
                columns={
                    @ColumnResult(name="id"),
                    @ColumnResult(name="name"),
                    @ColumnResult(name="orderCount"),
                    @ColumnResult(name="avgOrder", type=Double.class)})
        })
    

    Or you could convert FeedDetails to an interface and try Spring Data JPA Interface projection: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

    Or if you don't like these option there is a little library called QLRM: https://github.com/simasch/qlrm/blob/master/ConstructorResult.md

提交回复
热议问题