1. 通过ById等方法查询出来并进行设值,最后进行保存更新操作
- 查:通过Repository对象把实体根据ID查询出来
- 改:往查出来的实体对象进行set各个字段
- 存:通过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.
本文介绍了如何使用Spring Data JPA进行数据查询、修改和保存操作。首先通过Repository对象的ById方法获取实体,然后设置所需字段,最后利用save方法进行更新。另外,也提到了自定义SQL更新的方法,通过@Query和@Modifying注解来标记更新操作,并说明了返回值的意义。

2215

被折叠的 条评论
为什么被折叠?



