spring数据jpa-repository返回不同的类型

nwsw7zdq  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(368)

我有一个 CrudRepository 这样地:

  1. public interface TestTableRepository extends CrudRepository<TestTable, Long> {
  2. @Query(
  3. value = "select count(case when field1 = true then 1 end) as field1Count, count(case when field2 = true then 1 end) as field2Count from test_table",
  4. nativeQuery = true
  5. )
  6. List<Integer> selectRowCount();
  7. }

这是我的应用程序中类似查询的简化版本。什么是最好的回报类型使用?
正如当前编写的,实际返回的类型是 List<Object[]> 而不是 List<Integer> . 这怎么可能?我猜这与spring/hibernate在运行时构建的查询实现有关。

w1e3prcc

w1e3prcc1#

  1. **The best return type in this case is `Map<String, Object>`.<br/>
  2. To retrieve data from Map you can used alias name. In this case, key field1Count and field2Count will give you count value.**
  3. For Example
  4. @RestController class :
  5. @GetMapping("/getCount")
  6. public String getCounnt() {
  7. Map<String, Object> mp = userRepo.getCount();
  8. int field1CountValue = Integer.parseInt(mp.get("field1Count").toString());
  9. int field2CountValue = Integer.parseInt(mp.get("field2Count").toString());
  10. System.out.println("field1CountValue :"+field1CountValue+" field2CountValue :"+field2CountValue);
  11. return "field1CountValue :"+field1CountValue+" field2CountValue :"+field2CountValue;
  12. }
  13. ___________________________________
  14. @Repository Interface
  15. import java.util.Map;
  16. import org.springframework.data.jpa.repository.Query;
  17. import org.springframework.data.repository.CrudRepository;
  18. public interface UserRepo extends CrudRepository<User, Long>{
  19. @Query(
  20. value = "select count(case when id > 0 then 1 end) as field1Count, "
  21. + "count(case when id > 15 then 1 end) as field2Count from user",
  22. nativeQuery = true
  23. )
  24. Map<String, Object> getCount();
  25. }
  26. Console :
  27. [Hibernate: select count(case when id > 0 then 1 end) as field1Count, count(case when id > 15 then 1 end) as field2Count from user
  28. field1CountValue :9 field2CountValue :0]
展开查看全部

相关问题