Spring Data JPA : 改

1. 通过ById等方法查询出来并进行设值,最后进行保存更新操作

  1.    查:通过Repository对象把实体根据ID查询出来
  2.    改:往查出来的实体对象进行set各个字段
  3.    存:通过Repository接口的save方法进行保存
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FruitServiceImpl implements FruitService {

    @Autowired
    private FruitRepository fruitRepository;

    @Override
    public void edit(Fruit fruit) {
        // 把对象查出来,这个对象就有id主键
        Fruit newFruit = fruitRepository.getById(fruit.getId());

        // edit字段值
        newFruit.setColor(fruit.getColor());
        newFruit.setName(fruit.getName());

        // 保存
        fruitRepository.save(newFruit);

    }
}

 

2.自定义 参考 How do I update an entity using spring-data-jpa?

@Query:自定义sql

@Modifying:告诉spring-data-jps  这个sql是更新操作,需要用 executeUpdate() 而不是 executeQuery().

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface FruitRepository extends JpaRepository<Fruit, String>, JpaSpecificationExecutor<Fruit> {

    Fruit getById(Long id);
    
    @Modifying
    @Query("update Fruit f set f.name=:name  where f.color=:color")
    void updateFruits(@Param("name") String name, @Param("color") String color);

}

 

返回值

int : the number of records being updated.
boolean : true if there is a record being updated. Otherwise, false.

 

posted on 2020-06-15 14:38  dreamstar  阅读(137)  评论(0编辑  收藏  举报