Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

database - Spring data : CrudRepository's save method and update

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 interface doesn'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 registered 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...