spring-data-aop Repository层的增删查改
spring-data-aop Repository层的增删查改
先介绍一下spring-data-jpa repository层的传参,使用@Query时参数的运用
-
第一种
@Query("select new com.train.spr.entities.Content(b.billAmount, b.billDate, b.id, c.customerName) " + " from Bill b " + " join Customer c on b.customerId = c.id and c.id = ?1") List<Content> searchContent( Long id);按照顺序进行传参,使用第几个参数就在问号后写几,使用第二个参数就写
?2,使用第三个参数就写?3,以此类推。但是这种方式对于阅读代码不友好,不推荐使用 -
第二种,使用
@Param【推荐】import org.springframework.data.repository.query.Param; @Query("select new com.train.spr.entities.Content(b.billAmount, b.billDate, b.id, c.customerName) " + " from Bill b " + " join Customer c on b.customerId = c.id and c.id = :id") List<Content> searchContent(@Param("id") Long idValue);按照参数名传参,使用第什么参数就在冒号后写参数名,方便阅读代码
CURD 操作
- 增、删、改
@Modifying @Transactional @Query(value = "INSERT INTO your_table (column1, column2) VALUES (:v1, :v2)", nativeQuery = true) int insert(@Param("v1") String value1, @Param("v2") String value2); @Modifying @Query("delete from Customer c where c.id = :id") void delete(@Param("id") Long id); @Modifying @Query("update Customer c set c.customerName = :name where c.id = :id") void update(@Param("name") String name,@Param("id") Long id);⚠️ 注意
增、删、改 都需要在接口方法上加上
@Modifying注解,至于@Transactional,这个需要根据实际情况决定,如果执行的是一个事务,那么@Transactional最好加在service层,如果不需要事务,仅是单一操作,那么加在repository层的接口方法上 - 查
@Query("select c from Customer c where c.customerId = ?1") List<Customer> searchContent( Long id);
本文来自博客园,作者:勤匠,转载请注明原文链接:https://www.cnblogs.com/JarryShu/articles/18527831

浙公网安备 33010602011771号