Spring数据:CrudRepository的保存方法和更新 [英] Spring data : CrudRepository's save method and update
问题描述
我想知道如果 {save}
方法在 CrudRepository
中找到了条目,在数据库中:
@Repository
public interface ProjectDAO扩展CrudRepository< Project,Integer> {}
@Service
public class ProjectServiceImpl {
@Autowired private ProjectDAO pDAO;
public void save(Project p){pDAO.save(p);因此,如果我在已经注册的条目上调用该方法,它将会更新它,如果它找到一个改变的属性?
谢谢。
解决方案我想知道CrudRepository中的{save}方法是否已经在数据库中找到了条目,然后执行更新
Spring文档并不精确:
lockquote
保存给定的实体。使用返回的实例进行进一步操作
作为保存操作可能已经完全更改了实体实例
。
但是因为 CrudRepository
接口不提出另一种明确命名更新实体的方法,所以我们可能会认为是的,因为CRUD有望执行所有的CRUD操作(CREATE, READ,UPDATE,DELETE)。
这个假设得到了 SimpleJpaRepository
类的实现的证实这是 CrudRepository
的默认实现,它显示这两种情况都是由方法处理的:
@Transactional
public< S extends T> S save(S entity){
if(entityInformation.isNew(entity)){
em.persist(entity);
返回实体;
} else {
return em.merge(entity);
$ block $ $ $ b $ p $所以如果我打电话该方法在一个已经注册的条目中,如果它找到一个已更改的属性,它会更新
它?
它会执行在这种情况下合并操作。因此,所有字段都会根据如何设置合并级联和只读选项进行更新。
I wanted to know if the {save}
method in CrudRepository
do an update if it finds already the entry in the database like :
@Repository
public interface ProjectDAO extends CrudRepository<Project, Integer> {}
@Service
public class ProjectServiceImpl {
@Autowired private ProjectDAO pDAO;
public void save(Project p) { pDAO.save(p); } }
So if I call that method on an already registred entry, it'll update it if it finds a changed attribute ?
Thanks.
解决方案
I wanted to know if the {save} method in CrudRepository do an update
if it finds already the entry in the database
The Spring documentation about it is not precise :
Saves a given entity. Use the returned instance for further operations
as the save operation might have changed the entity instance
completely.
But as the CrudRepository
inteface doens't propose another method with an explicit naming for updating an entity, we may suppose that yes since CRUD is expected to do all CRUD operations (CREATE, READ, UPDATE, DELETE).
This supposition is confirmed by the implementation of the SimpleJpaRepository
class which is the default implementation of CrudRepository
which shows that both cases are handled by the method :
@Transactional
public <S extends T> S save(S entity) {
if (entityInformation.isNew(entity)) {
em.persist(entity);
return entity;
} else {
return em.merge(entity);
}
}
So if I call that method on an already registred entry, it'll update
it if it finds a changed attribute ?
It will do a merge operation in this case. So all fields are updated according to how the merging cascade and read only option are set.
这篇关于Spring数据:CrudRepository的保存方法和更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!