java - 代替DTO對象,java Spring Data JPA,JpaRepository返回的字元串列表

  显示原文与译文双语对照的内容
55 3

我有一個 interface 實現 JPARepository,有三個方法,其中一個是定製的@Query


public interface PersonRepository extends JpaRepository<Person, Long> {



 List<Person> getPersonBycountryCode(String countryCode);



 List<Person> findByCountryCodeAndCity(String string,String city);



 @Query(value ="SELECT person.firstName as firstName, person.lastName as lastName, person.countryCode as country, person.city as city,"


 +" SQRT(POWER((69.1 * (person.age - :age )), 2 )"


 +" + POWER((53 * (person.experience - :experience )), 2)) as eligibility"


 +" FROM Person person"


 +" ORDER BY eligibility ASC")


 List<PersonDetailsDto> findPersonDetailsByEligibility(


 @Param("age") BigDecimal age,


 @Param("experience") BigDecimal experience,


 Pageable pageable


 );


}



問題是:帶 @Query方法不返回 PersonDetailsDto 列表,而是返回字元串( List<List<String>> ) 列表列表。

PersonDetailsDto 是一個帶有 query ( 名字,姓氏,國家,城市,資格) query的POJO類,以及一個帶有所有變數的構造函數。 其他兩種方法返回Person對象的列表。

任何想法?

时间: 原作者:

147 5

實際上 JpaRepository<Person, Long> 意味著,你只能在jpa知識庫方法中使用Person作為你的dto 。

對於你的解決方案,你可以在存儲庫中定義你的dto介面:


public interface PersonRepository extends JpaRepository<Person, Long> {



 List<Person> getPersonBycountryCode(String countryCode);



 List<Person> findByCountryCodeAndCity(String string,String city);



 @Query(value ="SELECT person.firstName as firstName, person.lastName as lastName, person.countryCode as country, person.city as city,"


 +" SQRT(POWER((69.1 * (person.age - :age )), 2 )"


 +" + POWER((53 * (person.experience - :experience )), 2)) as eligibility"


 +" FROM Person person"


 +" ORDER BY eligibility ASC")


 List<PersonDetailsDto> findPersonDetailsByEligibility(


 @Param("age") BigDecimal age,


 @Param("experience") BigDecimal experience,


 Pageable pageable


 );



//define the interface here


 public interface PersonDetailsDto{


 public String getFirstName();


 public String getLastName();


 public String getCountry();


 public String getCity();


 public Integer getEligibility();


 }



}



143 3

在( 效率明智) 中,你可以通過這樣的方法來設置一個列或者所有列,以解決你的問題,這樣就可以從存儲庫類中設置 nativeQuery = true,這一點不錯:


public static final String FIND_SOMETHING ="SELECT somethingId, somethingName FROM something";



@Query(FIND_SOMETHING, nativeQuery = true)


public List<Object[]> findSomethings();



我希望這能幫助你解決你的問題。

原作者:
50 4

你可以在 @Query. 查詢中使用新關鍵字 並確保PersonDetailsDto具有適當的構造函數,並且還更改了包 NAME 。


@Query(value ="SELECT new com.company.PersonDetailsDto(person.firstName, person.lastName, person.countryCode, person.city,"


 +" SQRT(POWER((69.1 * (person.age - :age )), 2 )"


 +" + POWER((53 * (person.experience - :experience )), 2))"


 +" FROM Person person"


 +" ORDER BY eligibility ASC")


List<PersonDetailsDto> findPersonDetailsByEligibility(


 @Param("age") BigDecimal age,


 @Param("experience") BigDecimal experience,


 Pageable pageable


);



類似的回答問題。

原作者:
...