java - 查询方法参数转换异常

标签 java spring spring-data spring-data-jpa spring-data-rest

我正在尝试使用 spring-boot-starter-data-rest 通过 REST 访问 JPA 数据。 我想使用与 CrudRepository 不同的方法。但框架响应以下异常:

exception is org.springframework.data.repository.support.QueryMethodParameterConversionException: Failed to convert Brazil into hello.Country!] with root cause
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [@org.springframework.data.repository.query.Param hello.Country]

端点

http://localhost:8080/rest/cities/search/findByCountry?name=Brazil

CityRepository.java

@RepositoryRestResource(collectionResourceRel = "cities", path = "cities")
public interface  CityRepository extends CrudRepository<City, Long> {

    List<City> findByCountry(@Param("name") Country country);

}

City.java

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
@Table(name = "City")
public class City implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @JsonInclude(value=Include.ALWAYS)
    private long id;

    @NotNull
    @Column(name="name")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "country_id")
    @Embedded
    private Country country;

    protected City() {}

    public City(long id, String nome) {
        this.id = id;
        this.name = nome;
    }    

    public Country getCountry() {
        return country;
    }

Country.java

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
public class Country implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;

    @NotNull
    @Column(name = "name")
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy="country")
    private Set<City> cities;        

    protected Country() {}

    public Country(long id, String nome) {
        this.id = id;
        this.name = nome;
    }

当我打电话http://localhost:8080/rest/cities/时,我正常得到城市列表。我将 configureRepositoryRestConfiguration 设置为 config.setBasePath("/rest");

最佳答案

java.lang.String != hello.Country

根据文档,我们需要:

  1. Use ResponseBody with consumes

  2. 或者从 String 创建对象,如REST hello world example

关于java - 查询方法参数转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918927/

相关文章:

java - 如何延迟 bean,直到所有 spring 云连接器扫描完成?

java - 在 Windows 上运行 JAVA 8 jar,无需命令提示符

java - 为什么 Files.readAllBytes 首先读取 bufsize 为 1?

java - 使用 hibernate 保存集合字段

java - 在 Spring 框架中,从数据库中获取保存的实体以与修改后的未保存实体进行比较

java - 出现错误考虑在配置中定义类型为 'com.sam.cmsshoppingcart.models.PageRepository' 的 bean

java - org.hibernate.hql.internal.ast.tree.Node 在 jmap 堆转储中意味着什么

java - 尝试使用AvroParquetWriter写入S3时引发错误

java - 如何在 Spring 非托管类上使用@Value

spring - 如何在 spring-boot 应用程序启动期间创建多个 kafka 主题?