在使用JPQL查询从数据库中获取计数(不同的)值时,我被困住了。请参阅以下查询
我有桌子下面
111111 User_A Dell Inspiron15 in10
111112 User_A Dell Inspiron17 Win10
111113 User_A Dell Inspiron16 Win10
222221 User_B Dell Inspiron17 Win10
222222 User_B Dell Inspiron15 Win10
222223 User_B Lenovo Ideapad4 Win10
333331 User_C Lenovo Ideapad5 Win10
333332 User_C Lenovo Ideapad7 Win10
333333 User_C Dell Inspiron16 Win10
444441 User_D Dell Inspiron17 Win10
444442 User_D Lenovo Ideapad4 Win10
444443 User_D Lenovo Ideapad5 Win10使用下面的查询,我得到了以下输出
SELECT Laptop_Make, Laptop_Model, Laptop_OS, count(distict ID) as TOTAL group by Laptop_Make, Laptop_Model, Laptop_OS;
Dell Inspiron15 Win10 2
Dell Inspiron16 Win10 2
Dell Inspiron17 Win10 3
Lenovo Ideapad4 Win10 2
Lenovo Ideapad5 Win10 2
Lenovo Ideapad7 Win10 1如何将TOTAL列映射到Spring Entity,因为这个列不在物理表上,名称为膝上型计算机,并将输出表创建为json值列表
发布于 2022-04-05 09:19:01
除了Andronicus关于使用额外类的建议之外,另一个选项是使用javax.persistence.Tuple,如下所示:
List<Tuple> resultList = entitityManager
.createQuery("SELECT Laptop_Make, Laptop_Model, Laptop_OS, count(distict ID)) group by Laptop_Make, Laptop_Model, Laptop_OS", Tuple.class)
.getResultList();
List<JSONObject> allObjects = new ArrayList<>();
for(Tuple result : resultList) {
JSONObject object = new JSONObject();
object.put("make", (String) tuple.get(0));
object.put("model", (String) tuple.get(1));
object.put("os", (String) tuple.get(2));
object.put("total", (int) tuple.get(3));
allObjects.add(object);
}这为每个分组数据库条目提供了一个带有JSONObjects的列表。
发布于 2022-04-05 10:24:28
考虑到OP希望使用JPQL解决方案,下面的工作应该由以下人员来完成
public class LaptopAggregation {
private String laptopMake;
private String laptopModel;
private String laptopOS;
private Long total;
public LaptopAggregation(String laptopMake, String laptopModel,
String laptopOS, Long total) {
this.laptopMake = laptopMake;
this.laptopModel = laptopModel;
this.laptopOS = laptopOS;
this.total = total;
}
}您应该已经有了如下所示的实体
@Entity
public class Laptop {
@Id
private Long id;
private String laptopMake;
private String laptopModel;
private String laptopOS;
}现在,您还应该有一个Spring存储库,如下所示
public interface LaptopRepository extends JpaRepository<Laptop, Long> {
}然后,在最后提到的存储库类中,您可以添加以下方法,并且应该按照预期工作
@Query("SELECT " +
"new com.package.path.to.LaptopAggregation(lp.laptopMake, lp.laptopModel, lp.laptopOs, COUNT(lp.id)) " +
"FROM Laptop lp " +
"GROUP BY lp.laptopMake, lp.laptopModel, lp.laptopOS")
List<LaptopAggregation> findAggregateTotalLaptops();https://stackoverflow.com/questions/71748710
复制相似问题