sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  1796 随笔 :: 22 文章 :: 24 评论 :: 226万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

jpa 原生SQL写法

当你的抽象类继承了JpaRepository类时,就会拥有一些基本的增删改查操作。但是,很多时候只有这些简单的功能是不够的的,jpa也支持原生SQL和实体类SQL进行自定义查询。

简单例子:

@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);

Like表达式:

@Query(value = "select name,author,price from Book b where b.name like %:name%")
List<Book> findByNameMatch(@Param("name") String name);

原生SQL

使用Native SQL Query(nativeQuery=true则使用原生SQL默认HQL)

所谓本地查询,就是使用原生的sql语句(根据数据库的不同,在sql的语法或结构方面可能有所区别)进行查询数据库的操作

@Query(value = "select * from book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name);

实体类SQL

@Query(value = "SELECT new com.x3.schedule.saas.table.ScheduleUserView(" +
            " t2.userId, t1.title, t1.content, t1.completeTime, t2.scheduleState)" +
            " FROM ScheduleTable t1 LEFT JOIN ScheduleUserTable t2 ON t1.scheduleId = t2.scheduleId " +
            " WHERE t2.userId = ?1 AND t2.scheduleState = ?2")
    List<ScheduleUserView> findScheduleListByState(Long userId, int scheduleState);

使用@Param注解注入参数

@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author,
        @Param("price") long price);

SPEL表达式(使用时请参考最后的补充说明)

'#{#entityName}'值为'Book'对象对应的数据表名称(book)。

@Query(value = "select * from #{#entityName} b where b.name=?1", nativeQuery = true)
       List<Book> findByName(String name);

注:

1)update或delete时必须使用@Modifying和@Transactional对方法进行注解,才能使得ORM知道现在要执行的是写操作

2)有时候不加@Param注解参数,可能会报如下异常:

org.springframework.dao.InvalidDataAccessApiUsageException: Name must not be null or empty!; nested exception is java.lang.IllegalArgumentException: Name must not be null or empty!

3)当使用集合作为条件时,可参考此处的ids

@Transactional
@Modifying
@Query("update ShopCoupon sc set sc.deleted = true where sc.id in :ids")
public void deleteByIds(@Param(value = "ids") List<String> ids);

https://blog.csdn.net/weixin_40910372/article/details/108644851
posted on   sunny123456  阅读(674)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示