Spring boot jpa hibernate HQL query with group by gives Validation failed for query

随声附和 提交于 2021-01-07 06:59:47

问题


In spring boot app I have an ElementEntity:

....
@Entity
public class ElementEntity
{
    @Id
    int id;
    Double quantity;
    String form;
    String color;
    String type;
    String description;

    @ManyToOne
    @JoinColumn(name = "form")
    private FormEntity form;
}

And I have here FormEntity:

 @Entity
 public class FormEntity {
       .....
      @OneToMany
      @JoinColumn(name = "links")
      private List<LinksEntity> links;
    }

I want using HQL to generate a query that will sum the values of quantity field, group by color and and to return an list of [{qty, color, links}] I did this HQL query:

@Repository
public interface ElementRepository extends JpaRepository ... {


@Query("SELECT sum(quantity) as qty, color, form.links  FROM ElementEntity" +
        "WHERE type= ?1" +
        "GROUP BY color")
List<Object[]> findAllBy ElementAndGroup(String type);

This gives Validation failed for query for method public abstract findAllByElementAndGroup and it happens because of form.linkswhich is a @OneToMany relation.

How can I fix this query so I group the data by color and return the form links?


回答1:


Updated after question update

You can use join in your query. Don't forget to add the columns to group by:

@Query("SELECT sum(e.quantity) as qty, f.color, l.id  FROM ElementEntity e " +
        " join e.form f" + 
        " join f.links l " + 
        " WHERE e.type= ?1 " +
        " GROUP BY e.color, l.id")

In the code above I assumed that name of id field in FormEntity is id. Change form.id if the assumption isn't right.

Updates after discussion:

@Query("select sum(e.quantity), f  FROM ElementEntity e join e.form f where e.type = ?1  group by f ")
List<Object[]>findAllByElementAndGroup(String type);
final List<Object[]> aggregatedData = elementRepository.findAllByElementAndGroup("some type");
for (Object[] o : aggregatedData) {
     final Number quantitySum = (Number) o[0];
     final FormEntity form = (FormEntity) o[1];
}


来源:https://stackoverflow.com/questions/65325716/spring-boot-jpa-hibernate-hql-query-with-group-by-gives-validation-failed-for-qu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!