Spring 数据 REST 和自定义实体查找(提供的 ID 类型错误)

Spring Data REST and custom entity lookup (Provided id of the wrong type)

我有一个看起来像这样的模型:

@Entity
public class MyModel {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(unique = true, nullable = false)
    @RestResource(exported = false)
    private int pk;

    @Column(unique = true, nullable = false)
    private String uuid = UUID.randomUUID().toString();

    @Column(nullable = false)
    private String title;

    public int getPk() {
        return pk;
    }

    public void setPk(int pk) {
        this.pk = pk;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

如您所见,我有一个自动递增的 PK 作为我的模型 ID,还有一个随机 UUID。我想使用数据库中的PK作为主键,但想使用UUID作为public面向ID。 (用于 URL 等)

我的存储库如下所示:

@RepositoryRestResource(collectionResourceRel = "my-model", path = "my-model")
public interface MyModelRepository extends CrudRepository<MyModel, String> {

    @RestResource(exported = false)
    MyModel findByUuid(@Param("uuid") String id);
}

如您所见,我已将存储库设置为使用字符串作为 ID。

最后,我在这样的配置文件中设置了实体查找:

@Component
public class RepositoryEntityLookupConfig extends RepositoryRestConfigurerAdapter {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {

        config.withEntityLookup().forRepository(MyModelRepository.class, MyModel::getUuid, MyModelRepository::findByUuid);

    }
}

这对于 GET 和 POST 请求非常有效,但由于某种原因,我在 PUT 和 DELETE 方法上返回错误。

o.s.d.r.w.RepositoryRestExceptionHandler : Provided id of the wrong type for class MyModel. Expected: class java.lang.Integer, got class java.lang.String

有人知道是什么原因造成的吗?我不明白为什么它期待一个整数。

我可能在做一些愚蠢的事情,因为我对这个框架还很陌生。 感谢您的帮助。

您的域对象的标识符显然是 int 类型。这意味着,您的存储库需要声明为 extends CrudRepository<MyModel, Integer>.