SpringData如何通过@Query注解支持JPA语句和原生SQL语句
作者:qq_36722039 发布时间:2022-08-26 22:07:29
通过@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}'来作为数据表名使用。
来源:https://blog.csdn.net/qq_36722039/article/details/81124382


猜你喜欢
- 1,验证传入路径是否为正确的路径名(Windows系统,其他系统未使用)Java代码 // 验证字符串是否为正确路径名的正则表达式 
- 看到题目后,分析了下, 10的阶乘就已经很大了。计算出来再得到这个末尾的0的个数,完全不现实,即使实现了也是很麻烦的。后来想某个数的阶乘中乘
- 字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。深刻认识Stri
- 继承什么是继承呢?继承(Inheritance)是一种联结类与类的层次模型。指的是一个类(称为子类、子接口)继承另外的一个类(称为父类、父接
- 1.由于springboot集成了tomcat,所以打包的时候不再使用war,而是使用jar <groupId>cn&
- 一、为什么会存在动态内存int data=20;//在栈空间上开辟4个字节空间char ch[5]={0};//在栈开辟5个字节连续空间上面
- Android Notification 使用方法详解用TaskStackBuilder来获取PendingIntent处理点击跳转到别的A
- 一、什么是状态模式定义:当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。主要解决:当控制一个对象状态的条件表达式过于
- 网上有很多人探讨Java中异常捕获机制try...catch...finally块中的finally语句是不是一定会被执行?很多人都说不是,
- 1. 前言Android LayerDrawble 包含一个Drawable数组,系统将会按照这些Drawable对象的数组顺序来绘制他们,
- Java jar打包成exe应用程序,可在无JDK/JRE环境下运行老师让做一个小项目,但是需要打包发布出来,因此在网上查了很多资料之后总结
- 一个中大型的 Java 项目往往包含若干 JAR 包,这些 JAR 包有着不同的版本号。如果这些 JAR 包单独发布,然后直接通过版本号引用
- 前言记一次为了节省代码没有在方法体中声明HttpServletRequest,而用autowire直接注入所钻的坑结论:给心急的人。 直接在
- 协程源码的结构在研究Kotlin源码之前,得先搞懂Kotlin源码结构分布。不然找不到该看哪里的代码。看源码之前当然先得有一个目标,最好是带
- 概述在JAVA JDK8 List分组的实现和用法一文中介绍了JDK 8如何对list进行分组,但是没有提到如何在分组后,获取每个分组的第一
- 本文实例讲述了Android开发实现拨打电话与发送信息的方法。分享给大家供大家参考,具体如下:xml布局:<LinearLayout
- 国家气象局提供了三种数据的形式网址在:http://www.weather.com.cn/data/sk/101010100.htmlhtt
- 本文实例讲述了Android编程滑动效果之Gallery仿图像集浏览实现方法。分享给大家供大家参考,具体如下:Android系统自带一个Ga
- 本文实例为大家分享了WheelView实现上下滑动选择器的具体代码,供大家参考,具体内容如下1.获得wheelwheel是GitHub上的一
- 1.根据入参带分页参数进行sql查询分页 Criteria criteria = n