当前位置:   article > 正文

开发人员必须要掌握的《Spring Data JPA四种查询方式》_springdata jpa 用户权限查询

springdata jpa 用户权限查询

目录

一、SpringDataJPa

介绍springDataJPa

SpringDataJpa,jpa,hibernate之间的关系

二、搭建环境

1.创建Maven工程,导入坐标

2.编写SpringDataJPA的配置文件(applicationContext.xml)

3.创建实体类,数据库表

4.数据库表的SQL

5.DAO接口

三、四种查询方式:

1.基本的增删改查  

JpaRepository封装好的方法

JpaSpecificationExecutor封装好的方法

测试类

2.JPQL查询  

DAO接口:

测试类:

3.SQL查询

DAO接口

测试类:

4.方法命名查询

部分对照表

DAO接口:

测试类:


一、SpringDataJPa

介绍springDataJPa

Spring Data JPA 是 Spring 基于 ORM 框架、JPA 规范的基础上封装的一套JPA应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常用功能,且易于扩展!学习并使用 Spring Data JPA 可以极大提高开发效率!

Spring Data JPA 是更大的 Spring Data 系列的一部分,可以轻松实现基于 JPA 的存储库。该模块处理对基于 JPA 的数据访问层的增强支持。它使构建使用数据访问技术的 Spring 驱动的应用程序变得更加容易。

SpringDataJPA其实是对JPA规范的封装抽象,底层还是使用了Hibernate的JPA技术实现,引用JPQL(Java Persistence Query Language)查询语言,属于Spring整个生态体系的一部分。随着Spring Boot和Spring Cloud在市场上的流行,Spring Data JPA也逐渐进入大家的视野,它们组成有机的整体,使用起来比较方便,加快了开发的效率,使开发者不需要关心和配置更多的东西,完全可以沉浸在Spring的完整生态标准实现下。JPA上手简单,开发效率高,对对象的支持比较好,又有很大的灵活性,市场的认可度越来越高。

官网地址Spring Data JPA

SpringDataJpa,jpa,hibernate之间的关系

底层工作的还是Hibernate,听说啊,JPA与Hibernate的创始人是同一人。

image.png


二、搭建环境

1.创建Maven工程,导入坐标

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>JPA</artifactId>
  7. <groupId>com.dynamic</groupId>
  8. <version>1.0.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>JPA-Day2</artifactId>
  12. <properties>
  13. <spring.version>5.0.2.RELEASE</spring.version>
  14. <hibernate.version>5.0.7.Final</hibernate.version>
  15. <slf4j.version>1.6.6</slf4j.version>
  16. <log4j.version>1.2.12</log4j.version>
  17. <c3p0.version>0.9.1.2</c3p0.version>
  18. <mysql.version>5.1.6</mysql.version>
  19. </properties>
  20. <dependencies>
  21. <!-- junit单元测试 -->
  22. <dependency>
  23. <groupId>junit</groupId>
  24. <artifactId>junit</artifactId>
  25. <version>4.12</version>
  26. <scope>test</scope>
  27. </dependency>
  28. <!-- spring beg -->
  29. <dependency>
  30. <groupId>org.aspectj</groupId>
  31. <artifactId>aspectjweaver</artifactId>
  32. <version>1.6.8</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework</groupId>
  36. <artifactId>spring-aop</artifactId>
  37. <version>${spring.version}</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework</groupId>
  41. <artifactId>spring-context</artifactId>
  42. <version>${spring.version}</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.springframework</groupId>
  46. <artifactId>spring-context-support</artifactId>
  47. <version>${spring.version}</version>
  48. </dependency>
  49. <!-- spring对orm框架的支持包-->
  50. <dependency>
  51. <groupId>org.springframework</groupId>
  52. <artifactId>spring-orm</artifactId>
  53. <version>${spring.version}</version>
  54. </dependency>
  55. <dependency>
  56. <groupId>org.springframework</groupId>
  57. <artifactId>spring-beans</artifactId>
  58. <version>${spring.version}</version>
  59. </dependency>
  60. <dependency>
  61. <groupId>org.springframework</groupId>
  62. <artifactId>spring-core</artifactId>
  63. <version>${spring.version}</version>
  64. </dependency>
  65. <!-- spring end -->
  66. <!-- hibernate beg -->
  67. <dependency>
  68. <groupId>org.hibernate</groupId>
  69. <artifactId>hibernate-core</artifactId>
  70. <version>${hibernate.version}</version>
  71. </dependency>
  72. <dependency>
  73. <groupId>org.hibernate</groupId>
  74. <artifactId>hibernate-entitymanager</artifactId>
  75. <version>${hibernate.version}</version>
  76. </dependency>
  77. <dependency>
  78. <groupId>org.hibernate</groupId>
  79. <artifactId>hibernate-validator</artifactId>
  80. <version>5.2.1.Final</version>
  81. </dependency>
  82. <!-- hibernate end -->
  83. <!-- c3p0 beg -->
  84. <dependency>
  85. <groupId>c3p0</groupId>
  86. <artifactId>c3p0</artifactId>
  87. <version>${c3p0.version}</version>
  88. </dependency>
  89. <!-- c3p0 end -->
  90. <!-- log end -->
  91. <dependency>
  92. <groupId>log4j</groupId>
  93. <artifactId>log4j</artifactId>
  94. <version>${log4j.version}</version>
  95. </dependency>
  96. <dependency>
  97. <groupId>org.slf4j</groupId>
  98. <artifactId>slf4j-api</artifactId>
  99. <version>${slf4j.version}</version>
  100. </dependency>
  101. <dependency>
  102. <groupId>org.slf4j</groupId>
  103. <artifactId>slf4j-log4j12</artifactId>
  104. <version>${slf4j.version}</version>
  105. </dependency>
  106. <!-- log end -->
  107. <dependency>
  108. <groupId>mysql</groupId>
  109. <artifactId>mysql-connector-java</artifactId>
  110. <version>${mysql.version}</version>
  111. </dependency>
  112. <!-- spring data jpa 的坐标-->
  113. <dependency>
  114. <groupId>org.springframework.data</groupId>
  115. <artifactId>spring-data-jpa</artifactId>
  116. <version>1.9.0.RELEASE</version>
  117. </dependency>
  118. <dependency>
  119. <groupId>org.springframework</groupId>
  120. <artifactId>spring-test</artifactId>
  121. <version>${spring.version}</version>
  122. </dependency>
  123. <!-- el beg 使用spring data jpa 必须引入 -->
  124. <dependency>
  125. <groupId>javax.el</groupId>
  126. <artifactId>javax.el-api</artifactId>
  127. <version>2.2.4</version>
  128. </dependency>
  129. <dependency>
  130. <groupId>org.glassfish.web</groupId>
  131. <artifactId>javax.el</artifactId>
  132. <version>2.2.4</version>
  133. </dependency>
  134. <!-- el end -->
  135. </dependencies>
  136. </project>

2.编写SpringDataJPA的配置文件(applicationContext.xml)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
  12. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
  13. http://www.springframework.org/schema/data/jpa
  14. http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
  15. <!-- 1.dataSource 配置数据库连接池-->
  16. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  17. <property name="driverClass" value="com.mysql.jdbc.Driver" />
  18. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
  19. <property name="user" value="root" />
  20. <property name="password" value="root" />
  21. </bean>
  22. <!-- 2.配置entityManagerFactory -->
  23. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  24. <property name="dataSource" ref="dataSource" />
  25. <property name="packagesToScan" value="com.dynamic.domain" />
  26. <property name="persistenceProvider">
  27. <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
  28. </property>
  29. <!--jpa的供应商适配器 -->
  30. <property name="jpaVendorAdapter">
  31. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  32. <!--配置是否自动创建数据库表 -->
  33. <property name="generateDdl" value="false" />
  34. <!--指定数据库类型 -->
  35. <property name="database" value="MYSQL" />
  36. <!--数据库方言:支持的特有语法 -->
  37. <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
  38. <!--是否显示sql -->
  39. <property name="showSql" value="true" />
  40. </bean>
  41. </property>
  42. <!--jpa的方言 :高级的特性 -->
  43. <property name="jpaDialect" >
  44. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  45. </property>
  46. </bean>
  47. <!-- 3.事务管理器-->
  48. <!-- JPA事务管理器 -->
  49. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  50. <property name="entityManagerFactory" ref="entityManagerFactory" />
  51. </bean>
  52. <!-- 整合spring data jpa-->
  53. <jpa:repositories base-package="com.dynamic.dao"
  54. transaction-manager-ref="transactionManager"
  55. entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
  56. <!-- 4.txAdvice-->
  57. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  58. <tx:attributes>
  59. <tx:method name="save*" propagation="REQUIRED"/>
  60. <tx:method name="insert*" propagation="REQUIRED"/>
  61. <tx:method name="update*" propagation="REQUIRED"/>
  62. <tx:method name="delete*" propagation="REQUIRED"/>
  63. <tx:method name="get*" read-only="true"/>
  64. <tx:method name="find*" read-only="true"/>
  65. <tx:method name="*" propagation="REQUIRED"/>
  66. </tx:attributes>
  67. </tx:advice>
  68. <!-- 5.aop-->
  69. <!-- <aop:config>-->
  70. <!-- <aop:pointcut id="pointcut" expression="execution(* com.dynamic.service.*.*(..))" />-->
  71. <!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />-->
  72. <!-- </aop:config>-->
  73. <context:component-scan base-package="com.dynamic"></context:component-scan>
  74. <!--组装其它 配置文件-->
  75. </beans>

3.创建实体类,数据库表

  1. package com.dynamic.domain;
  2. import javax.persistence.*;
  3. /**
  4. * @Author: Promsing(张有博)
  5. * @Date: 2021/10/13 - 17:29
  6. * @Description: 客户的实体类
  7. * 配置映射关系
  8. * 1.实体类和表的映射关系
  9. * @Entity 声明是实体类
  10. * @Table(name = "cst_customer") 实体类与表的映射关系,name配置表的名称
  11. *
  12. * 2.实体类中属性和表字段的映射关系
  13. * @version: 1.0
  14. */
  15. @Entity
  16. @Table(name = "cst_customer")
  17. public class Customer {
  18. /**
  19. * @Id:声明主键的配置
  20. * @GeneratedValue:配置主键的生成策略
  21. * strategy
  22. * GenerationType.IDENTITY :自增,mysql
  23. * * 底层数据库必须支持自动增长(底层数据库支持的自动增长方式,对id自增)
  24. * GenerationType.SEQUENCE : 序列,oracle
  25. * * 底层数据库必须支持序列
  26. * GenerationType.TABLE : jpa提供的一种机制,通过一张数据库表的形式帮助我们完成主键自增
  27. * GenerationType.AUTO : 由程序自动的帮助我们选择主键生成策略
  28. * @Column:配置属性和字段的映射关系
  29. * name:数据库表中字段的名称
  30. */
  31. @Id
  32. @GeneratedValue(strategy = GenerationType.IDENTITY)
  33. @Column(name = "cust_id")
  34. private Long id;//主键
  35. @Column(name="cust_name")
  36. private String custName;
  37. @Column(name="cust_source")
  38. private String custSource;
  39. @Column(name = "cust_industry")
  40. private String custIndustry;//所属行业
  41. @Column(name="cust_level")
  42. private String custLevel;
  43. @Column(name = "cust_address")
  44. private String custAddress;
  45. @Column(name = "cost_phone")
  46. private String custPhone;
  47. public Long getId() {
  48. return id;
  49. }
  50. public void setId(Long id) {
  51. this.id = id;
  52. }
  53. public String getCustName() {
  54. return custName;
  55. }
  56. public void setCustName(String custName) {
  57. this.custName = custName;
  58. }
  59. public String getCustSource() {
  60. return custSource;
  61. }
  62. public void setCustSource(String custSource) {
  63. this.custSource = custSource;
  64. }
  65. public String getCustIndustry() {
  66. return custIndustry;
  67. }
  68. public void setCustIndustry(String custIndustry) {
  69. this.custIndustry = custIndustry;
  70. }
  71. public String getCustLevel() {
  72. return custLevel;
  73. }
  74. public void setCustLevel(String custLevel) {
  75. this.custLevel = custLevel;
  76. }
  77. public String getCustAddress() {
  78. return custAddress;
  79. }
  80. public void setCustAddress(String custAddress) {
  81. this.custAddress = custAddress;
  82. }
  83. public String getCustPhone() {
  84. return custPhone;
  85. }
  86. public void setCustPhone(String custPhone) {
  87. this.custPhone = custPhone;
  88. }
  89. @Override
  90. public String toString() {
  91. return "Customer{" +
  92. "id=" + id +
  93. ", custName='" + custName + '\'' +
  94. ", custSource='" + custSource + '\'' +
  95. ", custIndustry='" + custIndustry + '\'' +
  96. ", custLevel='" + custLevel + '\'' +
  97. ", custAddress='" + custAddress + '\'' +
  98. ", custPhone='" + custPhone + '\'' +
  99. '}';
  100. }
  101. }

4.数据库表的SQL

  1. CREATE TABLE `cst_customer` (
  2. `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  3. `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  4. `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  5. `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  6. `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  7. `cust_address` varchar(128) DEFAULT NULL COMMENT '客户联系地址',
  8. `cust_phone` varchar(64) DEFAULT NULL COMMENT '客户联系电话',
  9. `cost_phone` varchar(255) DEFAULT NULL,
  10. PRIMARY KEY (`cust_id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

5.DAO接口

  1. package com.dynamic.dao;
  2. import com.dynamic.domain.Customer;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. import org.springframework.data.jpa.repository.Modifying;
  6. import org.springframework.data.jpa.repository.Query;
  7. import java.util.List;
  8. /**
  9. * @Author: Promsing(张有博)
  10. * @Date: 2021/10/17 - 17:36
  11. * @Description: 需要符合springDataJPA的dao层接口规范
  12. * JpaRepository<操作的实体类型,实体类中主键属性的类型>
  13. * *封装了基本的CRUD操作
  14. * JpaSpecificationExecutor<操作的实体类型>
  15. * *封装了复杂查询(分页)
  16. * @version: 1.0
  17. */
  18. public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
  19. }

三、四种查询方式:

1.基本的增删改查  

继承JpaRepository,JpaSpecificationExecutor 接口,使用JPA封装好的方法。

JpaRepository封装好的方法

image.png

JpaSpecificationExecutor封装好的方法

image.png

测试类

  1. /**
  2. * findOne(id) :根据id查询
  3. *
  4. * save(customer):保存或更新 实体的id属性
  5. *
  6. * delete(id) :根据id删除
  7. *
  8. * findAll() :查询全部
  9. *
  10. * count() :计数
  11. *
  12. * exists() :判断是否存在
  13. *
  14. */
  15. @Test
  16. public void testFindOne(){
  17. System.out.println("dfa");
  18. Customer one = dao.findOne(1L);
  19. System.out.println(one);
  20. }
  21. @Test
  22. public void testSave(){
  23. System.out.println("dfa");
  24. Customer c=new Customer();
  25. c.setCustAddress("廊坊");
  26. c.setCustName("小小张");
  27. c.setCustPhone("9999");
  28. c.setCustLevel("vipp");
  29. Customer save = dao.save(c);
  30. System.out.println(save);
  31. }
  32. @Test
  33. @Transactional
  34. public void testUpdate(){
  35. System.out.println("dfa");
  36. Customer c=new Customer();
  37. c.setCustAddress("廊坊");
  38. c.setCustName("小小张");
  39. c.setCustPhone("2800");
  40. Customer save = dao.save(c);
  41. System.out.println(save);
  42. }
  43. @Test
  44. public void testDelete(){
  45. dao.delete(2L);
  46. System.out.println();
  47. }
  48. @Test
  49. @Transactional
  50. public void testFindAll(){
  51. List<Customer> all = dao.findAll();
  52. for (Customer customer : all) {
  53. System.out.println(customer);
  54. }
  55. System.out.println();
  56. }
  57. @Test
  58. @Transactional
  59. public void testCount(){
  60. long count = dao.count();
  61. System.out.println(count);
  62. }
  63. @Test
  64. public void testExists(){
  65. boolean exists = dao.exists(2L);
  66. System.out.println(exists);
  67. }
  68. @Test
  69. @Transactional
  70. public void testGetOne(){
  71. // getOone方法是懒加载
  72. Customer one = dao.getOne(2L);
  73. System.out.println(one);
  74. }

2.JPQL查询  

 jpa query language  (jpq查询语言),与原生SQL语句类似,并且完全面向对象,通过类名和属性访问,查询的是类和类中的属性

上一篇博客介绍了JPQL:

JPA入门案例完成增删改查_小小张自由—>张有博-CSDN博客JPA (Java Persistence API) Java持久化API。是一套Java官方制定的ORM方案。JPA是一种规范,一种标准,具体的操作交给第三方框架去实现,比如说Hibernate,OpenJPA等。本文介绍了ORM思想,JPA规范与实现,如何去搭建JPA的基础环境,JPA的操作步骤以及使用Java代码用JPA做基本数据的增删改查。https://blog.csdn.net/promsing/article/details/120794681

需要将JPQL语句配置到接口方法上

 1.特有的查询:需要在dao接口上配置方法

 2.在新添加的方法上,使用注解的形式配置jpql查询语句

 3.注解 : @Query

DAO接口:

  1. /**
  2. * @Author: Promsing(张有博)
  3. * @Date: 2021/10/17 - 17:36
  4. * @Description: 需要符合springDataJPA的dao层接口规范
  5. * JpaRepository<操作的实体类型,实体类中主键属性的类型>
  6. * *封装了基本的CRUD操作
  7. * JpaSpecificationExecutor<操作的实体类型>
  8. * *封装了复杂查询(分页)
  9. * @version: 1.0
  10. */
  11. public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
  12. /**
  13. * @Query:表示查询
  14. *
  15. * @Modifying 表示更新的操作
  16. */
  17. @Query(value = "from Customer where custName = ? ")
  18. public List<Customer> findJpql(String custName);
  19. /**
  20. * 对于多个占位符参数
  21. * 赋值的时候,默认情况下,占位符的位置需要和方法参数中的位置保持一致
  22. *
  23. * 可以指定占位符参数的位置
  24. * ? 索引的方式,指定此占位符的取值来源
  25. */
  26. @Query(value = "from Customer where custName = ? and id = ?")
  27. // @Query(value = "from Customer where custName = ?2 and id = ?1")
  28. public Object findCustNameAndId(String name,Long id);
  29. @Query(value = "update Customer set custName = ? where id = ? ")
  30. @Modifying //表示是,更新的操作
  31. public Integer updateName(String name,Long id);
  32. }

测试类:

  1. @Test
  2. public void testJpql(){
  3. List<Customer> list = dao.findJpql("小小张");
  4. System.out.println(list);
  5. }
  6. @Test
  7. public void testFindCustNameAndId(){
  8. Object one = dao.findCustNameAndId("小小张",1L);
  9. System.out.println(one);
  10. }
  11. @Test
  12. @Transactional //添加事务的支持
  13. @Rollback(value = false)
  14. /**
  15. * springDataJpa中使用jpql完成更新/删除操作
  16. * 需要手动添加事务的支持
  17. * 默认会执行结束之后,回滚事务
  18. * @Rollback: 设置是否自动回滚
  19. * false(不) | true
  20. */
  21. public void testUpdateName(){
  22. Object one = dao.updateName("张自由",3L);
  23. System.out.println(one);
  24. }

3.SQL查询

1.特有的查询:需要在dao接口上配置方法

  2.在新添加的方法上,使用注解的形式配置sql查询语句

  3.注解 : @Query

   value :jpql语句 | sql语句

   nativeQuery :false(使用jpql查询) | true(使用本地查询:sql查询)

DAO接口

  1. package com.dynamic.dao;
  2. import com.dynamic.domain.Customer;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. import org.springframework.data.jpa.repository.Modifying;
  6. import org.springframework.data.jpa.repository.Query;
  7. import java.util.List;
  8. /**
  9. * @Author: Promsing(张有博)
  10. * @Date: 2021/10/17 - 17:36
  11. * @Description: 需要符合springDataJPA的dao层接口规范
  12. * JpaRepository<操作的实体类型,实体类中主键属性的类型>
  13. * *封装了基本的CRUD操作
  14. * JpaSpecificationExecutor<操作的实体类型>
  15. * *封装了复杂查询(分页)
  16. * @version: 1.0
  17. */
  18. public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
  19. /**
  20. * 使用sql的形式查询 查询全部用户
  21. * SQL:select * from cst_customer
  22. * @Query: 配置sql查询
  23. * value:sqly语句
  24. * nativeQuery:查询方式
  25. * true:sql查询
  26. * false:jpql查询
  27. * @return
  28. */
  29. @Query(value = "select * from cst_customer", nativeQuery = true)
  30. public List<Customer> findSql();
  31. @Query(value = "select * from cst_customer where cust_name like ?", nativeQuery = true)
  32. public List<Customer> findLikeSql(String name );
  33. }

测试类:

  1. @Test
  2. public void testSQL(){
  3. List<Customer> list = dao.findSql();
  4. List<Customer> sql = dao.findLikeSql("小%");
  5. for (Customer customer : sql) {
  6. System.out.println(customer);
  7. }
  8. }

4.方法命名查询

是对jpql查询,更加深入一层的封装

  我们只需要按照SpringDataJpa提供的方法名称规则定义方法,不需要再配置jpql语句,完成查询

按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。

部分对照表

Keyword

Sample

JPQL

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnameIs,

findByFirstnameEquals

… where x.firstname = ?1

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

LessThan

findByAgeLessThan

… where x.age < ?1

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

After

findByStartDateAfter

… where x.startDate > ?1

Before

findByStartDateBefore

… where x.startDate < ?1

IsNull

findByAgeIsNull

… where x.age is null

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

Like

findByFirstnameLike

… where x.firstname like ?1

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

TRUE

findByActiveTrue()

… where x.active = true

FALSE

findByActiveFalse()

… where x.active = false

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

DAO接口:

  1. package com.dynamic.dao;
  2. import com.dynamic.domain.Customer;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. import org.springframework.data.jpa.repository.Modifying;
  6. import org.springframework.data.jpa.repository.Query;
  7. import java.util.List;
  8. /**
  9. * @Author: Promsing(张有博)
  10. * @Date: 2021/10/17 - 17:36
  11. * @Description: 需要符合springDataJPA的dao层接口规范
  12. * JpaRepository<操作的实体类型,实体类中主键属性的类型>
  13. * *封装了基本的CRUD操作
  14. * JpaSpecificationExecutor<操作的实体类型>
  15. * *封装了复杂查询(分页)
  16. * @version: 1.0
  17. */
  18. public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {
  19. /**
  20. * 方法名的约定
  21. *
  22. * findBy:查询
  23. * 对象中的属性名(首字母大写),查询条件
  24. *
  25. * findByCustName 根据客户名称查询
  26. *
  27. * 会根据方法名称进行解析 findBy from XXX where custName
  28. * @param name
  29. * @return
  30. */
  31. //1.findBy +属性名称(根据属性名称进行完成匹配的查询=)
  32. public Customer findByCustName(String name );
  33. //2.findBy +属性名称 +“查询方式”(Like | isNull)
  34. public List<Customer> findByCustNameLike(String name );
  35. //3.findBy +属性名称 +“查询方式” +“多条件的连接符(and|or)” +属性名 +“查询方式”
  36. public Customer findByCustNameLikeAndCustIndustry(String name,String industry);
  37. }

测试类:

  1. @Test
  2. public void testFindNaming(){
  3. Customer custName = dao.findByCustName("张自由");
  4. System.out.println(custName);
  5. System.out.println("______________");
  6. List<Customer> byCustNameLike = dao.findByCustNameLike("小%");
  7. for (Customer customer : byCustNameLike) {
  8. System.out.println(customer);
  9. }
  10. System.out.println("______________");
  11. Customer it = dao.findByCustNameLikeAndCustIndustry("小%", "IT教育");
  12. System.out.println(it);
  13. }

如果本篇博客对您有一定的帮助,大家记得留言+点赞+收藏哦。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/656253
推荐阅读
相关标签
  

闽ICP备14008679号