Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

spring - Update or SaveorUpdate in CRUDRespository, Is there any options available

I am trying to do CRUD operations with My Entity bean. CRUDRepository provide standard methods to find, delete and save but there is no generic method available like saveOrUpdate(Entity entity) that in turn calls Hibernate or HibernateTemplate sessions saveorUpdate() methods.

The way CRUDRepository provides this functionality is to use like this

@Modifying
@Query("UPDATE Space c SET c.owner = :name WHERE c.id = :id")
Integer setNameForId(@Param("name") String name, @Param("id")

but this is not generic and needs to be written for complete form fields. Please let me know if there is any way or i can get session of Hibernate or object of Spring HibernateTemplate to solve this issue.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The implementation of the method

<S extends T> S save(S entity)

from interface

CrudRepository<T, ID extends Serializable> extends Repository<T, ID>

automatically does what you want. If the entity is new it will call persist on the entity manager, otherwise it will call merge

The code looks like this:

public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

and can be found here. Note that SimpleJpaRepository is the class that automatically implements CrudRepository in Spring Data JPA.

Therefore, there is no need to supply a custom saveOrUpdate() method. Spring Data JPA has you covered.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...