zoukankan      html  css  js  c++  java
  • SpringData JPA 使用原生 SQL

    在实现个人博客系统的归档功能的时候,遇上这样的需求:

    1. 先把数据库中所有条目的时间按照年月分组,并查询出年月(String)的列表
    2. 根据年月字符串查询符合条件的博客,并返回博客列表

    由于数据访问层使用的SpringData JPA,所以一般是根据方法命名规则或者编写JPQL来查询数据库。

    但是上面两个需求光凭方法命名应该是很难实现,写简单的查询用 JPQL 还行,复杂的查询终究是感觉不如 SQL 顺畅,因此查了查在 JPA 中使用原生 SQL 的方法,总结在这里。

    先上代码:

    /* @Query("select function('date_format', b.updateTime, '%Y/%m') as ym
        from Blog b group by function('date_format', b.updateTime, '%Y/%m') order by ym") */
    @Query(value = "SELECT date_format(b.update_time, '%Y/%m') AS ym FROM t_blog b GROUP BY ym ORDER BY ym DESC",
            nativeQuery = true)
    List<String> findGroupYearMonth();
    
    @Query(value = "SELECT * FROM t_blog b WHERE date_format(b.update_time, '%Y/%m') = :yearmonth ORDER BY B.update_time DESC",
            nativeQuery = true)
    List<Blog> findBlogsByYearAndMonth(@Param("yearmonth") String yearMonth);
    

    主要有两点:

    1. 想使用原生 SQL 需要在@Query里加上nativeQuery = true
    2. 给原生 SQL 传递参数需要在方法参数里使用@Param("name"),然后在SQL中以:name形式填充。

    顺便在测试的时候还发现了一个小 tip:new出来的对象中如果有需要@Autowire的成员,是不会注入成功的。要么全部使用@Autowire

  • 相关阅读:
    linux如何查看ip地址
    mybais-plus整合springboot自动代码生成。
    org.springframework.beans.factory.UnsatisfiedDependencyException 问题
    springboot中使用AOP做访问请求日志
    springboot集成swagger
    springboot中的跨域问题
    spring中的ApplicationListener
    spring中的BeanDefinitionRegistryPostProcessor
    spring中的BeanFactoryPostProcessor
    servlet中ServletContainerInitializer
  • 原文地址:https://www.cnblogs.com/caophoenix/p/12919347.html
Copyright © 2011-2022 走看看