通常有商业问题来显示所有类别以及这些类别的使用频率。
查询很容易回答这个问题:
SELECT c.*, count(*) FROM category_assignment ca LEFT JOIN category c on ca.c_id = c.id group by c.id
我要求的是您建议的基于以下内容映射结果集的方法:
@Entity
public class CategoryAssignment {
@Id
int id;
@ManyToOne(fetch = FetchType.EAGER)
private Category category;
@ManyToOne(fetch = FetchType.EAGER)
private Car car;
}
@Entity
public class Category {
@Id
String id;
TypeEnum type;
...
}
@Entity
public class Car {
@Id
int id;
String name;
...
}
从我的观点来看,映射的最佳结果是获取一个自定义对象,该对象包含Category as实体,并且计数编号作为存储库调用之外的附加变量:
MappingResult result = repository.getCategoriesAndTheirCountOfType(TypeEnum type);
public class MappingResult {
Category category;
BigInteger count;
}
到目前为止我能够实现它的目的是手动映射结果集。但我希望有更简单的方法来映射它。
答案 0 :(得分:3)
您可以使用Projections获取它:
public interface CategoryAndCount {
Category getCategory();
Long getUsageCount();
}
public interface CategoryAssignmentRepository extends CrudRepository<CategoryAssignment, Integer> {
@Query("select c as category, count(*) as usageCount from CategoryAssignment ca join ca.category c where c.type = ?1 group by c")
CategoryAndCount getCategoriesAndTheirCountOfType(TypeEnum type);
}
请勿忘记在查询中为字段添加别名(c为类别,count(*)为 usageCount )。
答案 1 :(得分:0)
您可以按照以下两种方法之一将其作为Catgeory的财产。好处是该属性始终可用,您无需调用任何特定查询。
@OneToOne
-
@Entity
@Table(name = "categories")
@SecondaryTable(name = "category_summary_data", pkJoinColumns = {...})
public class Category {
@Id
String id;
TypeEnum type;
@Column(name = "usage_count", table = "category_summary_data", insertable = false, updateable = false)
// do not use int https://stackoverflow.com/questions/43407889/prefered-way-to-map-a-result-set-with-entity-and-count-using-spring-data/43411008#43411008
Integer usageCount;
}
@Formula
注释,您可以使用它来设置计算值。-
@Entity
@Table(name = "categories")
public class Category {
@Id
String id;
TypeEnum type;
@Formula("some sql to count the records")
int usageCount;
}