Spring Date JPA update some of the fields

In the Spring Data JPA, the new and updated operations are carried out with a save () way, JPA is to know by what method we want to insert or update it? After testing according save, JPA calling program () is a method of determining updata or insert operation is to see whether the primary key of the entity object is assigned. JPA will first inquire whether the primary key to have the ID database, if not found, then execute the insert method, on the contrary if found will perform the update method. About update some fields: JPA can only judge the implementation of insert or update, it can not determine whether we update some of the fields. So we have not been assigned field will be overwritten to NULL. Accordingly, when the target entity is updated by undesirable. JPA update fields There are two methods: 1. by providing a primary key save save (). Using the save () method updates the fields of physical objects must obtain Repository, the update operation on this object. 2. @Query implement complex sql statement via annotations. When performing update or delete method, you must add comments @Modifying and @Transactional.

1
2
3
4
5
6
7
8
9
@Modifying
@Transactional
@Query ( "update Test a set "  +
        "a.name = CASE WHEN :#{#testAre.name} IS NULL THEN a.name ELSE :#{#testAre.name} END ,"  +
        "a.age = CASE WHEN :#{#testAre.age} IS NULL THEN a.age ELSE :#{#testAre.age} END ,"  +
        "a.insertTime = CASE WHEN :#{#testAre.insertTime} IS NULL THEN a.insertTime ELSE :#{#testAre.insertTime} END ,"  +
        "a.spare =  CASE WHEN :#{#testAre.spare} IS NULL THEN a.spare ELSE :#{#testAre.spare} END "  +
        "where a.id = :#{#testAre.id}" )
int  update( @Param ( "testAre" ) TestAre testAre);

Guess you like

Origin www.cnblogs.com/moxiaotao/p/11576994.html