SpringData如何通过@Query注解支持JPA语句和原生SQL语句

 更新时间:2021年11月25日 16:13:59   作者:qq_36722039  
这篇文章主要介绍了SpringData如何通过@Query注解支持JPA语句和原生SQL语句,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

通过@Query注解支持JPA语句和原生SQL语句

在SpringData中们可是使用继承接口直接按照规则写方法名即可完成查询的方法,不需要写具体的实现,但是这样写又是不能满足我们的需求,比如子查询,SpringData中提供了@Query注解可以让我们写JPA的语句和原生的SQL语句,那接下来看看怎么写JPA的查询语句和原生的SQL语句。

package com.springdata.study.repository; 
import java.util.List; 
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param; 
import com.springdata.study.entitys.Person;
 
//1.实际上Repository是一个口接口,没有提供任何方法,是一个标记接口
//2.实现了Repository接口就会被spring IOC容器识别为Repository Bean
//  会被纳入IOC容器中
//3.Repository接口也可以同@RepositoryDefinition 注解代替,效果是一样的
//4.接口中的泛型:第一个是那个实体类的Repository,第二个是实体类的主键的类型
//@RepositoryDefinition(domainClass=Person.class,idClass=Integer.class)
 
/**
 * 在Repository接口中申明方法 1.申明方法需要符合一定的规范 2.查询方法需要以 find | read | get开头 3.涉及查询条件时
 * 需要用条件关键字连接 4.属性首字母大写 5.支持级联属性
 * 6.AddressId若当前实体类中有属性,则优先使用该属性,若想要使用级联属性,需要用下划线隔开Address_Id
 */ 
public interface PersonRepositoiry extends Repository<Person, Integer> {
 // select p from Person where p.name = ?
 Person getByName(String name);
 
 List<Person> findByNameStartingWithAndIdLessThan(String name, Integer id);
 
 // where name like %? and id < ?
 List<Person> findByNameEndingWithAndIdLessThan(String name, Integer id);
 
 // where email in ? age < ?
 List<Person> readByEmailInOrAgeLessThan(List<String> emails, int age);
 
 // 级联属性查询
 // where address.id > ?
 List<Person> findByAddress_IdGreaterThan(Integer is);
 
 // 可以使用@Query注解在其value属性中写JPA语句灵活查询
 @Query("SELECT p FROM Person p WHERE p.id = (SELECT max(p2.id) FROM Person p2)")
 Person getMaxIdPerson();
 
 // 在@Query注解中使用占位符
 @Query(value = "SELECT p FROM Person p where p.name = ?1 and p.email = ?2")
 List<Person> queryAnnotationParam1(String name, String email);
 
 // 使用命名参数传递参数
 @Query(value = "SELECT p FROM Person p where p.name = :name")
 List<Person> queryAnnotationParam2(@Param("name") String name);
 
 // SpringData可以在参数上添加%
 @Query("SELECT p FROM Person p WHERE p.name LIKE %?1%")
 List<Person> queryAnnotationLikeParam(String name);
 
 // SpringData可以在参数上添加%
 @Query("SELECT p FROM Person p WHERE p.name LIKE %:name%")
 List<Person> queryAnnotationLikeParam2(@Param("name")String name);
 
 //在@Query注解中添加nativeQuery=true属性可以使用原生的SQL查询
 @Query(value="SELECT count(*) FROM jpa_person", nativeQuery=true)
 long getTotalRow(); 
}

下面是这个类的测试类

package com.springdata.study.test; 
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List; 
import javax.sql.DataSource; 
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.springdata.study.entitys.Person;
import com.springdata.study.repository.PersonRepositoiry;
import com.springdata.study.service.PersonService;
 
public class DataSourceTest { 
 private ApplicationContext applicationContext;
 private PersonService personService;
 private PersonRepositoiry personRepositoiry;
 
 {
  applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  personRepositoiry = applicationContext.getBean(PersonRepositoiry.class);
  personService = applicationContext.getBean(PersonService.class);
 }
 
 @SuppressWarnings("resource")
 @Test
 public void testDataSource() throws SQLException {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  DataSource dataSource = applicationContext.getBean(DataSource.class);
  System.out.println(dataSource.getConnection());
 }
 
 @Test
 public void testSpringdata() {
  Object person = personService.getPerson("LQF");
  System.out.println(person);
 }
 
 @Test
 public void testFindByNameStartingWithAndIdLessThan() {
  List<Person> persons = personRepositoiry.findByNameStartingWithAndIdLessThan("g", 6);
  persons = personRepositoiry.findByNameEndingWithAndIdLessThan("g", 6);
  System.out.println(persons);
 }
 
 @Test
 public void testReadByEmailInOrAgeLessThan() {
  List<Person> persons = personRepositoiry.readByEmailInOrAgeLessThan(Arrays.asList("123@qq.com"), 25);
  System.out.println(persons);
 }
 
 @Test
 public void testFindByAddressIdGreaterThan() {
  personRepositoiry.findByAddress_IdGreaterThan(1);
 }
 
 @Test
 public void testGetMaxIdPerson() {
  Person person = personRepositoiry.getMaxIdPerson();
  System.out.println(person);
 }
 
 @Test
 public void testQueryAnnotationParam() {
  List<Person> persons = personRepositoiry.queryAnnotationParam1("liqingfeng", "123@qq.com");
  System.out.println(persons);
 }
 
 @Test
 public void testQueryAnnotationParam2() {
  List<Person> persons = personRepositoiry.queryAnnotationParam2("lqf");
  System.out.println(persons);
 }
 
 @Test
 public void testQueryAnnotationLikeParam() {
  List<Person> persons = personRepositoiry.queryAnnotationLikeParam2("li");
  System.out.println(persons);
 }
 
 @Test
 public void testGetTotalRow() {
  long count = personRepositoiry.getTotalRow();
  System.out.println(count);
 } 
}

@Query注解的用法(Spring Data JPA)

1.一个使用@Query注解的简单例子

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

2.Like表达式

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

3.使用Native SQL Query

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

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

4.使用@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);

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

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

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

6.一个较完整的例子

public interface BookQueryRepositoryExample extends Repository<Book, Long> {
    @Query(value = "select * from Book b where b.name=?1", nativeQuery = true) 
    List<Book> findByName(String name);// 此方法sql将会报错(java.lang.IllegalArgumentException),看出原因了吗,若没看出来,请看下一个例子
    @Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
    List<Book> findByPriceRange(long price1, long price2);
    @Query(value = "select name,author,price from Book b where b.name like %:name%")
    List<Book> findByNameMatch(@Param("name") String name);
    @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);
}

7.解释例6中错误的原因

因为指定了nativeQuery = true,即使用原生的sql语句查询。使用java对象'Book'作为表名来查自然是不对的。只需将Book替换为表名book。

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

补充说明:

有同学提出来了,例子5中用'#{#entityName}'为啥取不到值啊?

先来说一说'#{#entityName}'到底是个啥。从字面来看,'#{#entityName}'不就是实体类的名称么,对,他就是。

实体类Book,使用@Entity注解后,spring会将实体类Book纳入管理。默认'#{#entityName}'的值就是'Book'。

但是如果使用了@Entity(name = "book")来注解实体类Book,此时'#{#entityName}'的值就变成了'book'。

到此,事情就明了了,只需要在用@Entity来注解实体类时指定name为此实体类对应的表名。在原生sql语句中,就可以把'#{#entityName}'来作为数据表名使用。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java多线程CountDownLatch的实现

    Java多线程CountDownLatch的实现

    本文主要介绍了Java多线程CountDownLatch的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • 30w+数据使用RedisTemplate pipeline空指针NullPointerException异常分析

    30w+数据使用RedisTemplate pipeline空指针NullPointerException异常分析

    这篇文章主要为大家介绍了30w+数据使用RedisTemplate pipeline空指针NullPointerException异常分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • 使用vscode搭建javaweb项目的详细步骤

    使用vscode搭建javaweb项目的详细步骤

    我个人是很喜欢VsCode的,开源免费、功能全面,所以为了方便,我把我几乎所有的运行都集成到了VsCode上来,JavaWeb也不例外,下面这篇文章主要给大家介绍了关于使用vscode搭建javaweb项目的相关资料,需要的朋友可以参考下
    2022-11-11
  • 详谈Array和ArrayList的区别与联系

    详谈Array和ArrayList的区别与联系

    下面小编就为大家带来一篇详谈Array和ArrayList的区别与联系。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 完美解决Server returned HTTP response code:403 for URL报错问题

    完美解决Server returned HTTP response code:403 for URL报错问题

    在调用某个接口的时候,突然就遇到了Server returned HTTP response code: 403 for URL报错这个报错,导致获取不到接口的数据,下面小编给大家分享解决Server returned HTTP response code:403 for URL报错问题,感兴趣的朋友一起看看吧
    2023-03-03
  • Java微服务开发之Swagger详解

    Java微服务开发之Swagger详解

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步
    2021-10-10
  • 一文搞懂MyBatis多数据源Starter实现

    一文搞懂MyBatis多数据源Starter实现

    本文将实现一个MyBatis的Springboot的Starter包,引用这个Starter包后,仅需要提供少量配置信息,就能够完成MyBatis多数据源的初始化和使用,需要的小伙伴可以参考一下
    2023-04-04
  • 使用Java将字符串在ISO-8859-1和UTF-8之间相互转换

    使用Java将字符串在ISO-8859-1和UTF-8之间相互转换

    大家都知道在一些情况下,我们需要特殊的编码格式,如:UTF-8,但是系统默认的编码为ISO-8859-1,遇到这个问题,该如何对字符串进行两个编码的转换呢,下面小编给大家分享下java中如何在ISO-8859-1和UTF-8之间相互转换,感兴趣的朋友一起看看吧
    2021-12-12
  • Java实现表单提交(支持多文件同时上传)

    Java实现表单提交(支持多文件同时上传)

    本文介绍了Java、Android实现表单提交(支持多文件同时上传)的方法,具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01
  • Java之String[] args含义及作用

    Java之String[] args含义及作用

    这篇文章主要介绍了Java之String[] args含义及作用,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08

最新评论