zoukankan      html  css  js  c++  java
  • JPA的查询方法总结

    一、使用where条件
    上一篇我们使用JPA进行了数据源的访问,默认JPA已经实现了好几个接口可以调用。但是,在实际的业务中,查询语句不可避免地需要使用where、order by等语句。

    我们用商品数据来做例子,添加一个价格字段price,按价格范围查询,看看怎么来实现。

    方式一:通过方法名称来实现
    public interface GoodsRepository extends JpaRepository<Goods, Long> {
    List<Goods> findByPriceBetween(Double startPrice, Double endPrice);
    }
    Spring Data JPA 查询方法支持的关键字(可参考:https://docs.spring.io/spring-data/jpa/docs/2.2.x/reference/html/#repositories.query-methods)

    Table 2.2. Supported keywords inside method names

    方式二:通过自定义SQL来实现
    在现实中,可能会含有非常复杂的SQL语句,或者为了性能优化,我们需要自定义sql。JPA提供注解和XML配置这2中方式。

    public interface GoodsRepository extends JpaRepository<Goods, Long> {
    @Query(value = "select * from goods g where g.price between :startPrice and :endPrice", nativeQuery = true)
    List<Goods> findByPriceBetween(Double startPrice, Double endPrice);
    }
    二、order by查询
    使用order by也可以编写在方法名上,可以把以上例子改为

    public interface GoodsRepository extends JpaRepository<Goods, Long> {
    List<Goods> findByPriceBetweenOrderByPriceAsc(Double startPrice, Double endPrice);

    ————————————————
    版权声明:本文为CSDN博主「loophome」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/loophome/article/details/87186778

  • 相关阅读:
    Devexpress根据条件单元格变色以及根据条件设置单元格可编辑-记录
    批量更新事物加回滚
    批量更新
    Devexpress GridControl无限高度惹得祸
    C# 多语言国际化问题中的 CultureInfo
    配置linux服务器的防火墙,以CENTOS 为例(转载)
    关于Java的程序运行提醒
    用Eclipse跑Hadoop程序的注意事项
    Hadoop平台-错误收集附解决方案!
    unity3d之物体克隆
  • 原文地址:https://www.cnblogs.com/fengli9998/p/11904265.html
Copyright © 2011-2022 走看看