无法使用
native query
中的jpa repository
实现DTO投影。对于单个字段它可以工作,但对于多个字段则不起作用。
需要使用一些复杂的本机查询来实现此类投影。所以我只是揭露我在这两个领域场景中遇到的问题。
jpa 存储库
public interface CustomerDetailRepository extends JpaRepository<CustomerDetail, Integer>{
@Query(value = "SELECT first_name as 'firstName', last_name as 'lastName' FROM customer_details where id=?1 order by customerId desc limit 1", nativeQuery = true)
CustomCustomerDTO findById2(String id);
去上课
import java.io.Serializable;
public class CustomCustomerDTO implements Serializable{
private static final long serialVersionUID = 1334840937329153773L;
private String firstName;
private String lastName;
public CustomCustomerDTO(String firstName,String lastName) {
this.firstName = firstName;
this.lastName=lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
我收到以下异常响应:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [com.customer.beans.CustomCustomerDTO]
但是,如果我从
firstName
中删除任何一个字段,即 lastName
或 DTO
并同时从 native query
中删除,那么我就可以获得给出名字或姓氏的响应。
我希望在回复中包含这两个字段。
编辑:我也尝试过界面投影
public interface CustomerObject {
String getFirstName();
String getLastName();
}
但是我遇到了同样的异常。
我使用的是
jpa
版本1。所以,我将其更改为2。
但仅此还不够。
实际上,对于
native
查询(不是 JPQL
),DTO 类投影不起作用。仅界面投影有效。
我不明白具有单个字段的本机查询如何再次与具有单个字段的 DTO 类投影进行映射。如果尝试使用多个字段,则会抛出异常。我还包括了两个字段构造函数。这就是我在上面的问题中所问的。
至于解决方案,因为DTO类投影不适用于本机查询,所以在将JPA版本从1更改为2后,我还创建了投影接口:
public interface CustomerObject {
String getFirstName();
String getLastName();
}
注意此投影接口中的方法名称约定。所有必需的字段方法都附加有
get
。
并且在
jpa repository
中,我将 native query
结果集收集到了此接口参考。
@Query(value = "SELECT first_name as firstName, last_name as lastName FROM customer_details where id=?1 order by customerId desc limit 1", nativeQuery = true)
CustomerObject findById2(String id);
这解决了我的问题。