简体   繁体   English

Spring 数据 JPA - 存储库返回不同的类型

[英]Spring Data JPA - repository returns different type

I have a CrudRepository like this:我有一个像这样的CrudRepository

public interface TestTableRepository extends CrudRepository<TestTable, Long> {

    @Query(
            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",
            nativeQuery = true
    )
    List<Integer> selectRowCount();
    
}

This is a simplified version of a similar query in my application.这是我的应用程序中类似查询的简化版本。 What is the best return type to use?什么是最好的返回类型?

As it's currently written, the actual returned type is List<Object[]> instead of List<Integer> .正如目前所写,实际返回的类型是List<Object[]>而不是List<Integer> How is that possible?这怎么可能? I'm guessing it's something to do with the query implementation being constructed by Spring/Hibernate at runtime.我猜这与 Spring/Hibernate 在运行时构建的查询实现有关。

**The best return type in this case is `Map<String, Object>`.<br/>
To retrieve data from Map you can used alias name. In this case, key field1Count and field2Count will give you count value.**    
        
For Example
@RestController class :
            @GetMapping("/getCount")
                public String getCounnt() {
                    Map<String, Object> mp =  userRepo.getCount();
                    int field1CountValue = Integer.parseInt(mp.get("field1Count").toString());
                    int field2CountValue = Integer.parseInt(mp.get("field2Count").toString());  
                    System.out.println("field1CountValue :"+field1CountValue+" field2CountValue :"+field2CountValue);
                    return "field1CountValue :"+field1CountValue+" field2CountValue :"+field2CountValue;
                }
    ___________________________________
@Repository Interface
            import java.util.Map;
            import org.springframework.data.jpa.repository.Query;
            import org.springframework.data.repository.CrudRepository;
            
            public interface UserRepo extends CrudRepository<User, Long>{
            
                @Query(
                        value = "select count(case when id > 0 then 1 end) as field1Count, "
                                + "count(case when id > 15 then 1 end) as field2Count from user",
                        nativeQuery = true
                )
                Map<String, Object> getCount(); 
            }
Console :
[Hibernate: select count(case when id > 0 then 1 end) as field1Count, count(case when id > 15 then 1 end) as field2Count from user
field1CountValue :9 field2CountValue :0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM