JPA写原生SQL

JPA原生sql

  • 代码示例
@Repository
public interface ParticipantRepository extends JpaRepository<Participant,Long> {
    
    
    List<Participant> getByAppointmentId(Long appointmentId);

    int deleteByAppointmentId(Long appointmentId);

    Participant getById(Long id);

    List<Participant>getByUserId(String userId);

    /**
     * 根据appointmentids删除一组数据
     * @param appointmentIds
     */
    @Transactional
    @Modifying
    @Query(nativeQuery = true,value = "delete from participant where appointment_id in :appointmentIds")
    void deleteByAppointmentIds(@Param("appointmentIds") List<Long> appointmentIds);


}

  • 最后一个deleteByAppintmentIds方法是根据传入的一组appointmentid数据删除数据库所有匹配的结果。
  • @Transactional注解:开启事务,当sql语句执行的是更新、删除时一定要加
  • @Modifying注解:标识此方法执行的是更新、删除、插入操作;(JPA默认使用executeQuery()执行自定义的sql语句,当自定义的时update、insert、delete语句时,需要使用execute()执行,否则会报错)
  • @Query注解:用来写sql,nativeQuery = true说明写的sql是本地sql,不需要经过JPA二次翻译,value中的值为sql语句体

猜你喜欢

转载自blog.csdn.net/qq_42026590/article/details/111314468