我有 2 个连接的实体:项目和系统。该映射类似于 Project 类中的映射:
@ManyToOne
@JoinColumn(name = "system_id")
@NotNull
private System system;
我正在尝试使用 spring data-rest 来实现项目的基本 Rest API。诸如 GET 或更新简单属性之类的简单内容效果很好。但这个查询会带来困难:
PATCH /api/projects/1 HTTP/1.1
{
"name": "Name2",
"system": {
"id": 1
}
}
我希望此查询更改名称并更改链接的系统对象,但找不到执行此操作的方法。据我了解,可以使用额外查询更新链接,如下所述:https://www.baeldung.com/spring-data-rest-relationships 。但我需要保留旧版 API 接口(interface),因此我需要使该接口(interface)正常工作。 抛出的错误是:
Caused by: org.hibernate.HibernateException: identifier of an instance of com.company.resourceapi.entities.Project was altered from 3 to 1
更新。澄清一下:更新之前项目是
id: 1,
name: "Name1",
system_id: 2
在 PATCH 请求之后我想查看
id: 1,
name: "Name2",
system_id: 1
最佳答案
我想出了这个不太优雅的解决方案:
我像这样重写存储库中的 save
方法:
public class ProjectRepositoryImpl implements CustomSaveRepo<Project> {
@Autowired
private SystemRepository repository;
@Autowired
private EntityManager em;
@Transactional
@Override
public Project save(Project entity) {
// entity.system has the id from the request, in the same time it's managed entity.
if (entity.getSystem() != null) {
Long sysId = entity.getSystem().getId();
if (sysId != null) {
em.detach(entity.getSystem());
System system = repository.findById(sysId)
.orElseThrow(() -> new RuntimeException());
entity.setSystem(system );
}
}
entity.setUpdatedAt(new Date());
em.persist(entity);
return entity;
}
}
如果有人与我分享更好的解决方案,我将不胜感激。
关于java - 如何在 spring data-rest 中使用 PATCH 请求更新引用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62448402/