SpringBoot 与JPA结合中 JpaRepository 里自定义查询

mac2025-11-18  4

在 SpringBoot 结合 JPA使用的时候,既想运用 JPA 封装的一些黑科技,又有一部分sq想自己写,踩了不少坑,查了不少资料后进行了如下总结:

1、update/delete 的话需要 加上**@Modifying** 注解

2、查询自定义内容 需要加 nativeQuery = true

3、其他的查询直接按照规则起方法名即可。

import com.edu.henu.xsgvisit.domain.Reservation; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Map; public interface UserRepository extends JpaRepository<User, Long> { @Query("select a from User a where a.guid = ?1 and a.is_deleted = 0") Reservation getUserByGuid(String guid); @Query("select a from User a where a.is_deleted = 0") List<Reservation> findAll(); @Query(value = "select sum(visit_num) from user t where t.vtime=?2 and t.vdate=?1 and t.is_deleted = 0",nativeQuery = true) int findReservationsCountByVisit_dateAndVisit_time(String vdate, Integer vtime); @Modifying @Query(value = "update User a set a.is_deleted = 1 where a.guid = :guid") void deleteUserByGuid(@Param("guid") String guid); }

还有一个要注意的点:如果调用 update / delete 的话,请在Service层加注解 @Transactional

最新回复(0)