簡體   English   中英

Spring 數據 JPA - 存儲庫返回不同的類型

[英]Spring Data JPA - repository returns different type

我有一個像這樣的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();
    
}

這是我的應用程序中類似查詢的簡化版本。 什么是最好的返回類型?

正如目前所寫,實際返回的類型是List<Object[]>而不是List<Integer> 這怎么可能? 我猜這與 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