JPA写原生SQL

2022年10月7日12:15:56

JPA原生sql

  • 代码示例
@RepositorypublicinterfaceParticipantRepositoryextendsJpaRepository<Participant,Long>{
    List<Participant>getByAppointmentId(Long appointmentId);intdeleteByAppointmentId(Long appointmentId);

    ParticipantgetById(Long id);

    List<Participant>getByUserId(String userId);/**
     * 根据appointmentids删除一组数据
     * @param appointmentIds
     */@Transactional@Modifying@Query(nativeQuery=true,value="delete from participant where appointment_id in :appointmentIds")voiddeleteByAppointmentIds(@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语句体
  • 作者:山风岚岚丶
  • 原文链接:https://blog.csdn.net/qq_42026590/article/details/111314468
    更新时间:2022年10月7日12:15:56 ,共 806 字。