Spring Data JPA : 删
参考 Spring Data JPA – Derived Delete Methods
1.通过deletebBy+attribute 来命名删除方法, Derived methods can be defined as VERB + attribute defined in an entity
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository public interface FruitRepository extends JpaRepository<Fruit, String>, JpaSpecificationExecutor<Fruit> { Long deleteById(Long id); Long deleteByName(String name); }
调用 需要@Transactional 注解
import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class FruitServiceImpl implements FruitService { @Autowired private FruitRepository fruitRepository; @Override @Transactional public void deleteById(Long id) { Long count = fruitRepository.deleteById(id); } @Override @Transactional public void deleteByName(String name) { Long count = fruitRepository.deleteByName(name); } }
2.原生sql实现删除
如果字段太多导致 删除方法名太长 或者 比较复杂的业务情况,可以通过写原生sql来实现删除
We may come across a scenario that makes the derived method's name too big or that involves a SQL JOIN between unrelated entities.
在Repository层 用@Query注解做查询 @Query 默认是按对象查询,nativeQuery = true:按sql原生语句
增删改操作 需用要@Modifying注解和@Transactional注解,并且返回值只能是int或者Integer。
@Repository public interface FruitRepository extends JpaRepository<Fruit, Long> { @Modifying @Query("delete from Fruit f where f.name=:name or f.color=:color") List<int> deleteFruits(@Param("name") String name, @Param("color") String color); }
调用
@Transactional public void deleteFruits() { List<int> deletedFruitCount = fruitRepository.deleteFruits("apple","green"); }