主頁 > 軟體設計 > 開發人員必須要掌握的《Spring Data JPA四種查詢方式》

開發人員必須要掌握的《Spring Data JPA四種查詢方式》

2021-12-25 09:01:18 軟體設計

目錄

一、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工程,匯入坐標

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>JPA</artifactId>
        <groupId>com.dynamic</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>JPA-Day2</artifactId>
    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.6</mysql.version>
    </properties>

    <dependencies>
        <!-- junit單元測驗 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring對orm框架的支持包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring end -->

        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <!-- hibernate end -->

        <!-- c3p0 beg -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- c3p0 end -->

        <!-- log end -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- spring data jpa 的坐標-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- el beg 使用spring data jpa 必須引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
        <!-- el end -->
    </dependencies>



</project>

2.撰寫SpringDataJPA的組態檔(applicationContext.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!-- 1.dataSource 配置資料庫連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>

    <!-- 2.配置entityManagerFactory -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.dynamic.domain" />
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
        </property>
        <!--jpa的供應商配接器 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--配置是否自動創建資料庫表 -->
                <property name="generateDdl" value="false" />
                <!--指定資料庫型別 -->
                <property name="database" value="MYSQL" />
                <!--資料庫方言:支持的特有語法 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--是否顯示sql -->
                <property name="showSql" value="true" />
            </bean>
        </property>
        <!--jpa的方言 :高級的特性 -->
        <property name="jpaDialect" >
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>

    </bean>


    <!-- 3.事務管理器-->
    <!-- JPA事務管理器  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <!-- 整合spring data jpa-->
    <jpa:repositories base-package="com.dynamic.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>

    <!-- 4.txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 5.aop-->
<!--    <aop:config>-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.dynamic.service.*.*(..))" />-->
<!--        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />-->
<!--    </aop:config>-->

    <context:component-scan base-package="com.dynamic"></context:component-scan>

    <!--組裝其它 組態檔-->

</beans>

3.創建物體類,資料庫表

package com.dynamic.domain;

import javax.persistence.*;

/**
 * @Author: Promsing(張有博)
 * @Date: 2021/10/13 - 17:29
 * @Description: 客戶的物體類
 *            配置映射關系
 *              1.物體類和表的映射關系
     *            @Entity 宣告是物體類
     *            @Table(name = "cst_customer")  物體類與表的映射關系,name配置表的名稱
 *
 *               2.物體類中屬性和表欄位的映射關系
 * @version: 1.0
 */
@Entity
@Table(name = "cst_customer")
public class Customer {

    /**
     * @Id:宣告主鍵的配置
     * @GeneratedValue:配置主鍵的生成策略
     *      strategy
     *          GenerationType.IDENTITY :自增,mysql
     *                 * 底層資料庫必須支持自動增長(底層資料庫支持的自動增長方式,對id自增)
     *          GenerationType.SEQUENCE : 序列,oracle
     *                  * 底層資料庫必須支持序列
     *          GenerationType.TABLE : jpa提供的一種機制,通過一張資料庫表的形式幫助我們完成主鍵自增
     *          GenerationType.AUTO : 由程式自動的幫助我們選擇主鍵生成策略
     * @Column:配置屬性和欄位的映射關系
     *      name:資料庫表中欄位的名稱
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long id;//主鍵

    @Column(name="cust_name")
    private String custName;

    @Column(name="cust_source")
    private String custSource;

    @Column(name = "cust_industry")
    private String custIndustry;//所屬行業

    @Column(name="cust_level")
    private String custLevel;

    @Column(name = "cust_address")
    private String custAddress;

    @Column(name = "cost_phone")
    private String custPhone;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public String getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustAddress() {
        return custAddress;
    }

    public void setCustAddress(String custAddress) {
        this.custAddress = custAddress;
    }

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", custName='" + custName + '\'' +
                ", custSource='" + custSource + '\'' +
                ", custIndustry='" + custIndustry + '\'' +
                ", custLevel='" + custLevel + '\'' +
                ", custAddress='" + custAddress + '\'' +
                ", custPhone='" + custPhone + '\'' +
                '}';
    }
}

4.資料庫表的SQL

CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)',
  `cust_name` varchar(32) NOT NULL COMMENT '客戶名稱(公司名稱)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客戶資訊來源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客戶所屬行業',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客戶級別',
  `cust_address` varchar(128) DEFAULT NULL COMMENT '客戶聯系地址',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '客戶聯系電話',
  `cost_phone` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

5.DAO介面

package com.dynamic.dao;

import com.dynamic.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @Author: Promsing(張有博)
 * @Date: 2021/10/17 - 17:36
 * @Description: 需要符合springDataJPA的dao層介面規范
 *          JpaRepository<操作的物體型別,物體類中主鍵屬性的型別>
 *              *封裝了基本的CRUD操作
 *          JpaSpecificationExecutor<操作的物體型別>
 *              *封裝了復雜查詢(分頁)
 * @version: 1.0
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {


  

}

三、四種查詢方式:

1.基本的增刪改查

繼承JpaRepository,JpaSpecificationExecutor 介面,使用JPA封裝好的方法,

JpaRepository封裝好的方法

image.png

JpaSpecificationExecutor封裝好的方法

image.png

測驗類

 /**
     * findOne(id) :根據id查詢
     *
     * save(customer):保存或更新  物體的id屬性
     *
     * delete(id)  :根據id洗掉
     *
     * findAll()   :查詢全部
     *
     * count()   :計數
     *
     * exists()  :判斷是否存在
     *
     */   
@Test
    public void testFindOne(){
        System.out.println("dfa");
        Customer one = dao.findOne(1L);
        System.out.println(one);
    }

    @Test
    public void testSave(){
        System.out.println("dfa");
        Customer c=new Customer();
        c.setCustAddress("廊坊");
        c.setCustName("小小張");
        c.setCustPhone("9999");
        c.setCustLevel("vipp");
        Customer save = dao.save(c);
        System.out.println(save);
    }

    @Test
    @Transactional
    public void testUpdate(){
        System.out.println("dfa");
        Customer c=new Customer();
        c.setCustAddress("廊坊");
        c.setCustName("小小張");
        c.setCustPhone("2800");
        Customer save = dao.save(c);
        System.out.println(save);
    }

    @Test
    public void testDelete(){

        dao.delete(2L);
        System.out.println();
    }

    @Test
    @Transactional
    public void testFindAll(){

        List<Customer> all = dao.findAll();
        for (Customer customer : all) {
            System.out.println(customer);
        }
        System.out.println();
    }


    @Test
    @Transactional
    public void testCount(){

        long count = dao.count();
        System.out.println(count);

    }

    @Test
    public void testExists(){

        boolean exists = dao.exists(2L);
        System.out.println(exists);

    }
    @Test
    @Transactional
    public void testGetOne(){
        // getOone方法是懶加載
        Customer one = dao.getOne(2L);
        System.out.println(one);

    }

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介面:

/**
 * @Author: Promsing(張有博)
 * @Date: 2021/10/17 - 17:36
 * @Description: 需要符合springDataJPA的dao層介面規范
 *          JpaRepository<操作的物體型別,物體類中主鍵屬性的型別>
 *              *封裝了基本的CRUD操作
 *          JpaSpecificationExecutor<操作的物體型別>
 *              *封裝了復雜查詢(分頁)
 * @version: 1.0
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {



    /**
     * @Query:表示查詢
     *
     * @Modifying 表示更新的操作
     */
    @Query(value = "from Customer where custName = ? ")
    public List<Customer> findJpql(String custName);


    /**
     * 對于多個占位符引數
     *    賦值的時候,默認情況下,占位符的位置需要和方法引數中的位置保持一致
     *
     *  可以指定占位符引數的位置
     *      ? 索引的方式,指定此占位符的取值來源
     */
    @Query(value = "from Customer where custName = ? and id = ?")
   // @Query(value = "from Customer where custName = ?2 and id = ?1")
    public Object findCustNameAndId(String name,Long id);



    @Query(value = "update Customer set custName = ? where id = ? ")
    @Modifying //表示是,更新的操作
    public Integer updateName(String name,Long id);


}

測驗類:

@Test
    public void testJpql(){

        List<Customer> list = dao.findJpql("小小張");
        System.out.println(list);

    }

    @Test
    public void testFindCustNameAndId(){

        Object one = dao.findCustNameAndId("小小張",1L);
        System.out.println(one);

    }

    @Test
    @Transactional //添加事務的支持
    @Rollback(value = false)
    /**
     * springDataJpa中使用jpql完成更新/洗掉操作
     *              需要手動添加事務的支持
     *              默認會執行結束之后,回滾事務
     * @Rollback: 設定是否自動回滾
     *             false(不)  | true
     */
    public void testUpdateName(){

        Object one = dao.updateName("張自由",3L);
        System.out.println(one);

    }

3.SQL查詢

1.特有的查詢:需要在dao介面上配置方法

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

3.注解 : @Query

value :jpql陳述句 | sql陳述句

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

DAO介面

package com.dynamic.dao;

import com.dynamic.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @Author: Promsing(張有博)
 * @Date: 2021/10/17 - 17:36
 * @Description: 需要符合springDataJPA的dao層介面規范
 *          JpaRepository<操作的物體型別,物體類中主鍵屬性的型別>
 *              *封裝了基本的CRUD操作
 *          JpaSpecificationExecutor<操作的物體型別>
 *              *封裝了復雜查詢(分頁)
 * @version: 1.0
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {



    /**
     * 使用sql的形式查詢  查詢全部用戶
     *    SQL:select * from cst_customer
     * @Query: 配置sql查詢
     *    value:sqly陳述句
     *    nativeQuery:查詢方式
     *        true:sql查詢
     *        false:jpql查詢
     * @return
     */
    @Query(value = "select * from cst_customer", nativeQuery = true)
    public List<Customer> findSql();
    

    @Query(value = "select * from cst_customer where  cust_name like ?", nativeQuery = true)
    public List<Customer> findLikeSql(String name   );



}

測驗類:

 @Test
    public void testSQL(){
        List<Customer> list = dao.findSql();

        List<Customer> sql = dao.findLikeSql("小%");
        for (Customer customer : sql) {
            System.out.println(customer);
        }

    }

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介面:

package com.dynamic.dao;

import com.dynamic.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @Author: Promsing(張有博)
 * @Date: 2021/10/17 - 17:36
 * @Description: 需要符合springDataJPA的dao層介面規范
 *          JpaRepository<操作的物體型別,物體類中主鍵屬性的型別>
 *              *封裝了基本的CRUD操作
 *          JpaSpecificationExecutor<操作的物體型別>
 *              *封裝了復雜查詢(分頁)
 * @version: 1.0
 */
public interface CustomerDao extends JpaRepository<Customer,Long>, JpaSpecificationExecutor<Customer> {



    /**
     * 方法名的約定
     *
     *        findBy:查詢
     *        物件中的屬性名(首字母大寫),查詢條件
     *
     *        findByCustName  根據客戶名稱查詢
     *
     *          會根據方法名稱進行決議 findBy  from XXX where custName
     * @param name
     * @return
     */
    //1.findBy +屬性名稱(根據屬性名稱進行完成匹配的查詢=)
    public Customer findByCustName(String name   );

    //2.findBy +屬性名稱 +“查詢方式”(Like | isNull)
    public List<Customer> findByCustNameLike(String name   );

    //3.findBy +屬性名稱 +“查詢方式” +“多條件的連接符(and|or)” +屬性名 +“查詢方式”
    public Customer findByCustNameLikeAndCustIndustry(String name,String industry);


}

測驗類:

 @Test
    public void testFindNaming(){

        Customer custName = dao.findByCustName("張自由");
         System.out.println(custName);

        System.out.println("______________");

        List<Customer> byCustNameLike = dao.findByCustNameLike("小%");
        for (Customer customer : byCustNameLike) {
            System.out.println(customer);
        }

        System.out.println("______________");
        Customer it = dao.findByCustNameLikeAndCustIndustry("小%", "IT教育");
        System.out.println(it);
    }

如果本篇博客對您有一定的幫助,大家記得留言+點贊+收藏哦,

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392178.html

標籤:其他

上一篇:摸魚時卷王在瘋狂刷題,這我可忍不了-<移除鏈表元素>

下一篇:你有多久沒有堅持過一件事情了?如果沒有就來刷一輪力扣LeetCode

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 面試突擊第一季,第二季,第三季

    第一季必考 https://www.bilibili.com/video/BV1FE411y79Y?from=search&seid=15921726601957489746 第二季分布式 https://www.bilibili.com/video/BV13f4y127ee/?spm_id_fro ......

    uj5u.com 2020-09-10 05:35:24 more
  • 第三單元作業總結

    1.前言 這應該是本學期最后一次寫作業總結了吧。總體來說,對作業的節奏也差不多掌握了,作業做起來的效率也更高了。雖然和之前的作業一樣,作業中都要用到新的知識,但是相比之前,更加懂得了如何利用工具以及資料。雖然之間卡過殼,但總體而言,這幾次作業還算完成的比較好。 2.作業程序總結 相比前兩個單元,此單 ......

    uj5u.com 2020-09-10 05:35:41 more
  • 北航OO(2020)第四單元博客作業暨課程總結博客

    北航OO(2020)第四單元博客作業暨課程總結博客 本單元作業的架構設計 在本單元中,由于UML圖具有比較清晰的樹形結構,因此我對其中需要進行查詢操作的元素進行了包裝,在樹的父節點中存盤所有孩子的參考。考慮到性能問題,我采用了快取機制,一次查詢后盡可能快取已經遍歷過的資訊,以減少遍歷次數。 本單元我 ......

    uj5u.com 2020-09-10 05:35:48 more
  • BUAA_OO_第四單元

    一、UML決議器設計 ? 先看下題目:第四單元實作一個基于JDK 8帶有效性檢查的UML(Unified Modeling Language)類圖,順序圖,狀態圖分析器 MyUmlInteraction,實際上我們要建立一個有向圖模型,UML中的物件(元素)可能與同級元素連接,也可與低級元素相連形成 ......

    uj5u.com 2020-09-10 05:35:54 more
  • 6.1邏輯運算子

    邏輯運算子 1. && 短路與 運算式1 && 運算式2 01.運算式1為true并且運算式2也為true 整體回傳為true 02.運算式1為false,將不會執行運算式2 整體回傳為false 03.只要有一個運算式為false 整體回傳為false 2. || 短路或 運算式1 || 運算式2 ......

    uj5u.com 2020-09-10 05:35:56 more
  • BUAAOO 第四單元 & 課程總結

    1. 第四單元:StarUml檔案決議 本單元采用了圖模型決議UML。 UML檔案可以抽象為圖、子圖、邊的邏輯結構。 在實作中,圖的節點包括類、介面、屬性,子圖包括狀態圖、順序圖等。 采用了三次遍歷UML元素的方法建圖,第一遍遍歷建點,第二、三次遍歷設定屬性、連邊,實作圖物件的初始化。這里借鑒了一些 ......

    uj5u.com 2020-09-10 05:36:06 more
  • 談談我對C# 多型的理解

    面向物件三要素:封裝、繼承、多型。 封裝和繼承,這兩個比較好理解,但要理解多型的話,可就稍微有點難度了。今天,我們就來講講多型的理解。 我們應該經常會看到面試題目:請談談對多型的理解。 其實呢,多型非常簡單,就一句話:呼叫同一種方法產生了不同的結果。 具體實作方式有三種。 一、多載 多載很簡單。 p ......

    uj5u.com 2020-09-10 05:36:09 more
  • Python 資料驅動工具:DDT

    背景 python 的unittest 沒有自帶資料驅動功能。 所以如果使用unittest,同時又想使用資料驅動,那么就可以使用DDT來完成。 DDT是 “Data-Driven Tests”的縮寫。 資料:http://ddt.readthedocs.io/en/latest/ 使用方法 dd. ......

    uj5u.com 2020-09-10 05:36:13 more
  • Python里面的xlrd模塊詳解

    那我就一下面積個問題對xlrd模塊進行學習一下: 1.什么是xlrd模塊? 2.為什么使用xlrd模塊? 3.怎樣使用xlrd模塊? 1.什么是xlrd模塊? ?python操作excel主要用到xlrd和xlwt這兩個庫,即xlrd是讀excel,xlwt是寫excel的庫。 今天就先來說一下xl ......

    uj5u.com 2020-09-10 05:36:28 more
  • 當我們創建HashMap時,底層到底做了什么?

    jdk1.7中的底層實作程序(底層基于陣列+鏈表) 在我們new HashMap()時,底層創建了默認長度為16的一維陣列Entry[ ] table。當我們呼叫map.put(key1,value1)方法向HashMap里添加資料的時候: 首先,呼叫key1所在類的hashCode()計算key1 ......

    uj5u.com 2020-09-10 05:36:38 more
最新发布
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:20:47 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:20:25 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:20:17 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:20:10 more
  • 【中介者設計模式詳解】C/Java/JS/Go/Python/TS不同語言實作

    * 中介者模式是一種行為型設計模式,它可以用來減少類之間的直接依賴關系,
    * 將物件之間的通信封裝到一個中介者物件中,從而使得各個物件之間的關系更加松散。
    * 在中介者模式中,物件之間不再直接相互互動,而是通過中介者來中轉訊息。 ......

    uj5u.com 2023-04-20 08:19:44 more
  • 露天煤礦現場調研和交流案例分享

    他們集團的資訊化公司及研究院在一個礦區正在做智能礦山的統一平臺的 試點,專案投資大概1億,包括了礦山的各方面的內容,顯示得我們這次交流有點多余。他們2年前開始做智能礦山的規劃,有很多煤礦行業專家的加持,他們的描述是非常完美,但是去年底應該上線的平臺,現在還沒有看到影子。他們確實有很多場景需求,但是被... ......

    uj5u.com 2023-04-20 08:19:07 more
  • 《社區人員管理》實戰案例設計&個人案例分享

    設計是一個讓人夢想成真程序,開始編碼、測驗、除錯之前進行需求分析和架構設計,才能保證關鍵方面都做正確 ......

    uj5u.com 2023-04-20 08:18:57 more
  • 軟體架構生態化-多角色交付的探索實踐

    作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基于此我們探索了一種新的技術體系及交付方案來解決如上問題。 ......

    uj5u.com 2023-04-20 08:18:49 more
  • 05單件模式

    #經典的單件模式 public class Singleton { private static Singleton uniqueInstance; //一個靜態變數持有Singleton類的唯一實體。 // 其他有用的實體變數寫在這里 //構造器宣告為私有,只有Singleton可以實體化這個類! ......

    uj5u.com 2023-04-19 08:42:51 more
  • 【架構與設計】常見微服務分層架構的區別和落地實踐

    軟體工程的方方面面都遵循一個最基本的道理:沒有銀彈,架構分層模型更是如此,每一種都有各自優缺點,所以請根據不同的業務場景,并遵循簡單、可演進這兩個重要的架構原則選擇合適的架構分層模型即可。 ......

    uj5u.com 2023-04-19 08:42:41 more