Spring Boot 无法将本机查询结果转换为DTO投影

c0vxltue  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(64)

无法在jpa repository中使用native query实现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);

字符串

dto类

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]


但是,如果我从DTO中删除任何一个字段,即firstNamelastName,同时从native query中删除,那么我就可以得到响应,给出first_name或last_name。
我希望这两个领域在我的回答。

  • edit:* 我还尝试了接口投影
public interface CustomerObject {
     String getFirstName();
     String getLastName();
}


但我得到了同样的例外。

kg7wmglp

kg7wmglp1#

我不知道为什么我的问题被否决了。无论如何,let_there_be_peace,也让我展示的解决方案,为我工作。
我使用的是jpa版本1。所以,我将其更改为2。
但仅仅这样还不够。
实际上,对于native查询(不是JPQL),DTO类投影不起作用。只有接口投影起作用。
我不明白具有单个字段的本地查询如何管理与DTO类投影的Map,如果尝试使用多个字段,则会抛出异常。我还包含了两个字段的构造函数。这就是我在上面的问题中所问的。
至于解决方案,因为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);


这解决了我的问题。

相关问题