Spring Data JPA 删除

参考 Spring Data JPA – Derived Delete Methods

1.通过deletebBy+attribute 来命名删除方法, Derived methods can be defined as VERB + attribute defined in an entity

1
2
3
4
@Repository
public interface FruitRepository extends JpaRepository<Fruit, Long> {
    Long deleteByName(String name);
}

调用 需要@Transactional 注解

1
2
3
4
5
@Transactional
public void deletedByName() {
 
    Long deletedFruitCount = fruitRepository.deleteByName("apple");
}

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。

1
2
3
4
5
6
@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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
import org.springframework.transaction.annotation.Transactional;
 
 
@Repository
public interface StudentRepository extends JpaRepository<Student, Long>, JpaSpecificationExecutor<Student> {
 
 
    @Modifying
    @Query(value = "update t_student set name = :name where id = :id ", nativeQuery = true)
    @Transactional
    Integer updateStudent(@Param("id") Long id, @Param("name") String name);
}