PSQLException: ERROR: column "drink1_.id" must appear in GROUP BY clause or used in aggregate function

huangapple go评论142阅读模式
英文:

PSQLException: ERROR: column "drink1_.id" must appear in GROUP BY clause or used in aggregate function

问题

I am writing a REST MVC web-application with Spring Boot, Hibernate, and PostgreSQL. I need to get the 6 most popular drinks out of all the carts I have. To do this, I first wrote a query in SQL:

SELECT drink_id, sum(count) as count
FROM cart_items
GROUP BY drink_id
ORDER BY 2 DESC
LIMIT 6

There is a result and this code worked well:
PSQLException: ERROR: column "drink1_.id" must appear in GROUP BY clause or used in aggregate function

Since I am working with JPA-repositories, I decided to write the same query in HQL. I wrote the request, but I had to remove LIMIT for a while since I didn't know how to implement it in HQL.

@Query("select C.drink, sum(C.count) as count from CartItem C group by C.drink order by 2 DESC")
Page<Drink> getMostPopularDrinks(Pageable pageable);

Then I decided to write a method for the output to check what I got:

Service:

public PageDTO<DrinkDTO> findAllDrinks(int page, int pageSize) {
    PageRequest pageRequest = PageRequest.of(page, pageSize);
    Page<Drink> drinkList = cartItemRepository.getMostPopularDrinks(pageRequest);
    return new PageDTO<>(drinkMapper.drinksToDrinksDTO(drinkList));
}

Controller:

@GetMapping("/drinks")
public PageDTO<DrinkDTO> getAllDrinks(@RequestParam(value = "page", defaultValue = "0") int page,
                                     @RequestParam(value = "page_size", defaultValue = "2") int pageSize) {
    return drinkService.findAllDrinks(page, pageSize);
}

CartItem Entity:

@Getter
@Setter
@Entity
@NoArgsConstructor
@Table(name = "cart_items")
public class CartItem {
    // ... (other fields and annotations)
}

Drink Entity:

@Data
@Entity
@NoArgsConstructor
@Table(name = "drink")
@Inheritance(strategy = InheritanceType.JOINED)
public class Drink {
    // ... (other fields and annotations)
}

But unfortunately, I got an error. The error message indicates that the column "drink1_.id" must appear in the GROUP BY clause or be used in an aggregate function. This issue seems to be related to the construction of your query in HQL.

Please note that the logs provided are not complete, and there might be more information that could help diagnose the issue. If you need further assistance, feel free to provide more details about the specific error you are facing, and I'll do my best to help.

英文:

I am writing a REST MVC web-application with Spring Boot, Hibernate and PostgreSQL. I need to get the 6 most popular drinks out of all the carts I have. To do this, I first wrote a query in SQL:

SELECT drink_id, sum(count) as count
FROM cart_items
GROUP BY drink_id
ORDER BY 2 DESC
LIMIT 6

There is a result and this code worked well:
PSQLException: ERROR: column "drink1_.id" must appear in GROUP BY clause or used in aggregate function

Since I am working with JPA-repositories, I decided to write the same query in HQL. I wrote the request, but I had to remove LIMIT for a while, since I didn't know how to implement it in HQL.

@Query(&quot;select C.drink, sum(C.count) as count from CartItem C group by C.drink order by 2 DESC&quot;)
Page&lt;Drink&gt; getMostPopularDrinks(Pageable pageable);

Then I decided to write a method for the output to check what I got:
Service:

public PageDTO&lt;DrinkDTO&gt; findAllDrinks(int page, int pageSize) {

        PageRequest pageRequest = PageRequest.of(page, pageSize);

        Page&lt;Drink&gt; drinkList = cartItemRepository.getMostPopularDrinks(pageRequest);

        return new PageDTO&lt;&gt;(drinkMapper.drinksToDrinksDTO(drinkList));
    }

Controller:

@GetMapping(&quot;/drinks&quot;)
public PageDTO&lt;DrinkDTO&gt; getAllDrinks(@RequestParam(value = &quot;page&quot;, defaultValue = &quot;0&quot;) int page,
                                      @RequestParam(value = &quot;page_size&quot;, defaultValue = &quot;2&quot;) int pageSize) {

        return drinkService.findAllDrinks(page, pageSize);
    }

СartItem Entity:

@Getter
@Setter
@Entity
@NoArgsConstructor
@Table(name = &quot;cart_items&quot;)
public class CartItem {


    @Data
    @Embeddable
    @NoArgsConstructor
    @AllArgsConstructor
    public static class CartId implements Serializable {

        private Long order_id;

        private Long drink_id;
    }


    /**
     * @EmbeddedId
     */
    @EmbeddedId
    private CartId cartId;

    @ManyToOne
    @JoinColumn(name = &quot;order_id&quot;, referencedColumnName = &quot;id&quot;,
            nullable = false, insertable = false, updatable = false)
    private Order order;

    @ManyToOne
    @JoinColumn(name = &quot;drink_id&quot;, referencedColumnName = &quot;id&quot;,
            nullable = false, insertable = false, updatable = false)
    private Drink drink;

    private int count;
}

Drink Entity:

@Data
@Entity
@NoArgsConstructor
@Table(name = &quot;drink&quot;)
@Inheritance(strategy = InheritanceType.JOINED)
public class Drink {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private BigDecimal price;

    private String about;

    private int weight;

    @Column(name = &quot;is_deleted&quot;)
    private boolean isDeleted;

    @ManyToOne
    @JoinColumn(name = &quot;packaging_id&quot;)
    private Packaging packaging;

    @ManyToOne
    @JoinColumn(name = &quot;manufacturer_id&quot;)
    private Manufacturer manufacturer;

    @ManyToOne
    @JoinColumn(name = &quot;country_id&quot;)
    private Country country;

But unfortunately I got an error, I don’t know what to do!

org.postgresql.util.PSQLException: ERROR: column &quot;drink1_.id&quot; must appear in GROUP BY clause or used in aggregate function
  Postition: 116
	at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2532) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2267) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:312) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:153) ~[postgresql-42.2.14.jar:42.2.14]
	at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:103) ~[postgresql-42.2.14.jar:42.2.14]
	at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) ~[HikariCP-3.4.5.jar:na]
	at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
	at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.getResultSet(Loader.java:2285) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2038) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2000) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.doQuery(Loader.java:951) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:352) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.doList(Loader.java:2831) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.doList(Loader.java:2813) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2645) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.Loader.list(Loader.java:2640) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1412) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1565) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.query.Query.getResultList(Query.java:165) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.springframework.data.jpa.repository.query.JpaQueryExecution$PagedExecution.doExecute(JpaQueryExecution.java:177) ~[spring-data-jpa-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88) ~[spring-data-jpa-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:154) ~[spring-data-jpa-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:142) ~[spring-data-jpa-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor$QueryMethodInvoker.invoke(QueryExecutorMethodInterceptor.java:195) ~[spring-data-commons-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152) ~[spring-data-commons-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:130) ~[spring-data-commons-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:367) ~[spring-tx-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149) ~[spring-data-jpa-2.3.1.RELEASE.jar:2.3.1.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at com.sun.proxy.$Proxy142.getMostPopularDrinks(Unknown Source) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.8.RELEASE.jar:5.2.8.RELEASE]
	at com.sun.proxy.$Proxy80.getMostPopularDrinks(Unknown Source) ~[na:na]
	at ru.coffeetearea.service.DrinkService.findAllDrinks(DrinkService.java:106) ~[main/:na]
	at ru.coffeetearea.controller.DrinkController.getAllDrinks(DrinkController.java:56) ~[main/:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
	at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at ru.coffeetearea.security.jwt.JwtTokenFilter.doFilter(JwtTokenFilter.java:33) ~[main/:na]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.7.RELEASE.jar:5.2.7.RELEASE]
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

NEW LOGS:

2020-08-23 18:07:56.951 ERROR 6296 --- [           main] o.h.hql.internal.ast.ErrorTracker        :  Unable to locate appropriate constructor on class [ru.coffeetearea.dto.NewDrinkDTO]. Expected arguments are: ru.coffeetearea.model.Drink, long
[cause=org.hibernate.PropertyNotFoundException: no appropriate constructor in class: ru.coffeetearea.dto.NewDrinkDTO]
2020-08-23 18:07:56.956 ERROR 6296 --- [           main] o.h.hql.internal.ast.ErrorTracker        :  Unable to locate appropriate constructor on class [ru.coffeetearea.dto.NewDrinkDTO]. Expected arguments are: ru.coffeetearea.model.Drink, long
[cause=org.hibernate.PropertyNotFoundException: no appropriate constructor in class: ru.coffeetearea.dto.NewDrinkDTO]

org.hibernate.hql.internal.ast.DetailedSemanticException: Unable to locate appropriate constructor on class [ru.coffeetearea.dto.NewDrinkDTO]. Expected arguments are: ru.coffeetearea.model.Drink, long
	at org.hibernate.hql.internal.ast.tree.ConstructorNode.resolveConstructor(ConstructorNode.java:182) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.tree.ConstructorNode.prepare(ConstructorNode.java:144) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.HqlSqlWalker.processConstructor(HqlSqlWalker.java:1258) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExpr(HqlSqlBaseWalker.java:2390) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectExprList(HqlSqlBaseWalker.java:2256) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectClause(HqlSqlBaseWalker.java:1518) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:597) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:325) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:273) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:276) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:192) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.engine.query.spi.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:113) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.engine.query.spi.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:73) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:162) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:604) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:716) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:113) ~[hibernate-core-5.4.17.Final.jar:5.4.17.Final]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
	```

</details>


# 答案1
**得分**: 0

你需要在查询和类投影中使用 `join` 来映射你的数据

仅获取 Id 和 count

```java
@Query("select new com.example.dto.DrinkDTO(dr.id, sum(ci.count)) from CartItem ci join ci.drink dr " 
       + "group by dr.id order by sum(ci.count) DESC")
Page<DrinkDTO> getMostPopularDrinks(Pageable pageable);

投影类

class DrinkDTO {
   
   private Integer drinkId;

   private long count;
   
   public DrinkDTO(Integer drinkId, long count) {
      this.drinkId = drinkId;
      this.count = count;
   }       

   // getter, setter
}

获取带有 count 的 Drink 实体

@Query("select new com.example.dto.DrinkDTO(dr, sum(ci.count)) from CartItem ci join ci.drink dr " 
       + "group by dr order by sum(ci.count) DESC")
Page<DrinkDTO> getMostPopularDrinks(Pageable pageable);

投影类

class DrinkDTO {
   
   private Drink drink;

   private long count;
   
   public DrinkDTO(Drink drink, long count) {
     this.drink = drink;
     this.count = count;
  }  
   //getter, setter
}
英文:

You need to use join in query and class projection to map your data

Fetch only Id and count

@Query(&quot;select new com.example.dto.DrinkDTO(dr.id, sum(ci.count)) from CartItem ci join ci.drink dr &quot; 
+ &quot;group by dr.id order by sum(ci.count) DESC&quot;)
Page&lt;DrinkDTO&gt; getMostPopularDrinks(Pageable pageable);

Projection class

class DrinkDTO {
private Integer drinkId;
private long count;
public DrinkDTO(Integer drinkId, long count) {
this.drinkId = drinkId;
this.count = count;
}       
// getter, setter
}

Fetch Drink enity with count

@Query(&quot;select new com.example.dto.DrinkDTO(dr, sum(ci.count)) from CartItem ci join ci.drink dr &quot; 
+ &quot;group by dr order by sum(ci.count) DESC&quot;)
Page&lt;DrinkDTO&gt; getMostPopularDrinks(Pageable pageable);

Projection class

class DrinkDTO {
private Drink drink;
private long count;
public DrinkDTO(Drink drink, long count) {
this.drink = drink;
this.count = count;
}  
//getter, setter
}

答案2

得分: 0

以下是翻译好的内容:

  @Query("select C.drink.id, sum(C.count) as count from CartItem C group by C.drink order by 2 DESC")
  List<Long> getMostPopularDrinksIds();
英文:

It is not important for me to get exactly drinks directly from the database, you can also drink ID. After receiving the ID, I can find them in the same database, so I slightly changed my request.

  @Query(&quot;select C.drink.id, sum(C.count) as count from CartItem C group by C.drink order by 2 DESC&quot;)
  List&lt;Long&gt; getMostPopularDrinksIds();

huangapple
  • 本文由 发表于 2020年8月23日 20:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63546735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定