错误converternotfoundexception springboot java

zpjtge22  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(478)

我正在使用springboot创建api来调用列表中的所有省份。首先我创建一个实体类

package example.parameter.entity;

import lombok.Data;

import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.List;

@Data
@Entity
@Table(name = "provinces",indexes = {
        @Index(name = "PROVINCES_INDX_0", columnList = "name")
})
public class Province extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "provinces_generator")
    @SequenceGenerator(name = "provinces_generator", sequenceName = "provinces_seq", allocationSize = 1)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @Column(name = "is_deleted")
    private Boolean isDeleted;

    @OneToMany(mappedBy = "province", cascade=CascadeType.ALL, orphanRemoval = true)
    private List<Regency> regencies;

    @NotBlank
    @Column(name = "name")
    private String name;
}

然后我创建了一个

package example.parameter.api.response;

import lombok.Data;

@Data
public class ProvinceResponseDTO {

    private String id;
    private String name;

}

然后创建存储库

package example.parameter.repository;

import example.parameter.api.response.ProvinceResponseDTO;
import example.parameter.entity.Province;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface ProvinceRepository extends JpaRepository<Province,Long> {

    public List<ProvinceResponseDTO> findAllByIsDeleted(Boolean isDeleted);

}

当我尝试使用api时,我在数据层遇到了这个错误。

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [example.parameter.entity.Province] to type [example.api.response.ProvinceResponseDTO]

我不知道这是怎么回事,有什么解决办法吗?

ozxc1zmp

ozxc1zmp1#

part:1
从方法名创建的jparepository查询应具有实体对象的默认返回类型。在您的案例中,您的存储库是为省实体提供的。所以,应该是这样的

public interface ProvinceRepository extends JpaRepository<Province, Long> {

    public List<Province> findAllByIsDeleted(Boolean isDeleted);

}

reference:- httpshttp://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/jparepository.html
第2部分
如果需要从方法名返回查询创建中的自定义对象,那么可以使用动态投影,如below:-

public interface ProvinceRepository extends JpaRepository<Province, Long> {

    public <T> List<T> findAllByIsDeleted(Boolean isDeleted, Class<T> dynamicClassType);

}

调用此方法时,定义如下

provinceRepository.findAllByIsDeleted(true, ProvinceResponseDTO.class)

reference:- https://docs.spring.io/spring data/jpa/docs/current/reference/html/#projections.dtos

相关问题