Spring Data REST 和自定义实体查找(提供错误类型的 id) [英] Spring Data REST and custom entity lookup (Provided id of the wrong type)
问题描述
我有一个看起来像这样的模型:
I have a model that looks something like this:
@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 作为面向公众的 ID.(用于网址等)
As you can see I have an auto-incrementing PK as my ID for the model, but also a random UUID. I want to use the PK in the database as the primary key, but want to use the UUID as a public facing ID. (To be used in URLs etc.)
我的存储库如下所示:
@RepositoryRestResource(collectionResourceRel = "my-model", path = "my-model")
public interface MyModelRepository extends CrudRepository<MyModel, String> {
@RestResource(exported = false)
MyModel findByUuid(@Param("uuid") String id);
}
如您所见,我已将存储库设置为使用字符串作为 ID.
As you can see I've set the repository to use a String as the ID.
最后,我在这样的配置文件中设置了实体查找:
Finally I set the entity lookup in a config file like this:
@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 方法上返回了一个错误.
This works perfectly well for GET and POST requests, but for some reason I get an error returned on PUT and DELETE methods.
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
有谁知道这可能是什么原因造成的?我不明白为什么它期待一个整数.
Anyone know what might be causing this? I don't understand why it's expecting an Integer.
我可能在做一些愚蠢的事情,因为我对这个框架还很陌生.感谢您的帮助.
I may be doing something stupid as I'm quite new to the framework. Thanks for any help.
推荐答案
域对象的标识符显然是 int
类型.这意味着,您的存储库需要声明为 extends CrudRepository
.
The identifier of your domain object is obviously of type int
. That means, your repository needs to be declared as extends CrudRepository<MyModel, Integer>
.
这篇关于Spring Data REST 和自定义实体查找(提供错误类型的 id)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!