SpringData自定义操作

news2024/9/23 11:20:28

一、JPQL和SQL

查询

package com.kuang.repositories;

import com.kuang.pojo.Customer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;

import java.util.List;

//extends CrudRepository<Customer,Long>
public interface CustomerRepository extends PagingAndSortingRepository<Customer,Long> {
    //增删查改


    //查询
    @Query("from Customer where custName=?1")
    List<Customer> findCustomerByCustName(String custName);
    //查询
    @Query("from Customer where custName=:custName")
    List<Customer> findCustomerByCustName1(@Param("custName") String custName);

}

二、规定方法名 

三、自定义操作--Query By Example

 CustomerQueryByExampleRepository.java

package com.kuang.repositories;

import com.kuang.pojo.Customer;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;

import java.util.List;


public interface CustomerQueryByExampleRepository extends PagingAndSortingRepository<Customer, Long> , QueryByExampleExecutor<Customer> {




}
QueryByExampleTest
package com.kuang.test;

import com.kuang.config.ApplicationConfig;
import com.kuang.pojo.Customer;
import com.kuang.repositories.CustomerQueryByExampleRepository;
import com.kuang.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@ContextConfiguration(classes = ApplicationConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class QueryByExampleTest {
    @Autowired
    private CustomerQueryByExampleRepository repository;

    @Test
    public void test01() {
        Customer customer = new Customer();
        customer.setCustName("lzl");
        customer.setCustAddress("为鲁斯");
    //通过Example构建查询条件  动态查询
        Example<Customer> of = Example.of(customer);
        List<Customer> list = (List<Customer>) repository.findAll(of);
        System.out.println(list);
    }

    /**
     * 通过匹配器 进行条件的限制
     * 简单实例 客户名称 客户地址动态查询
     *
     */
    @Test
    public void test02() {
        Customer customer = new Customer();
        customer.setCustName("徐庶");
        customer.setCustAddress("斯");
        //通过Example构建查询条件  动态查询
        ExampleMatcher matching = ExampleMatcher.matching().withIgnorePaths("custName")
                .withMatcher("custAddress", ExampleMatcher.GenericPropertyMatchers.endsWith());//针对单个条件进行设置
//                .withMatcher("custAddress", new ExampleMatcher.MatcherConfigurer<ExampleMatcher.GenericPropertyMatcher>() {
//                    @Override
//                    public void configureMatcher(ExampleMatcher.GenericPropertyMatcher matcher) {
//                        matcher.endsWith();
//                    }
//                });
              //  .withStringMatcher(ExampleMatcher.StringMatcher.ENDING);//对所有条件字符串进行结尾匹配

        Example<Customer> of = Example.of(customer,matching);
        List<Customer> list = (List<Customer>) repository.findAll(of);
        System.out.println(list);
    }
}

四、自定义操作--QueryDSL 操作方便 第三方 支持JDBC mongoDB 很多

需要导入依赖整合前面的springdata-jpa

<!--     querydsl-jpa   -->

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.4.0</version>
        </dependency>

完整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>springdata</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>02-springdata-jpa</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <querydsl.version>4.4.0</querydsl.version>
        <apt.version>1.1.3</apt.version>
    </properties>

    <dependencies>
        <!--    Junit    -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--   hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.32.Final</version>
        </dependency>
        <!--        mysql  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--        jpa  -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <!--     连接池   -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--     spring -  test    -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.10</version>
            <scope>test</scope>
        </dependency>

<!--     querydsl-jpa   -->

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>${querydsl.version}</version>
        </dependency>
    </dependencies>

<!--  这个插件是为了让程序自动生成query type (查询实体,命名方式为:"Q"+对应实体名) maven插件 -->
    <build>
        <plugins>
            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>${apt.version}</version>
                <dependencies>
                    <dependency>
                        <groupId>com.querydsl</groupId>
                        <artifactId>querydsl-apt</artifactId>
                        <version>${querydsl.version}</version>
                    </dependency>
                </dependencies>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources/queries</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                            <logOnlyOnError>true</logOnlyOnError>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>



</project>

编译一下,就出来了

需要设置为代码文件夹,才能够编译 

定义接口

package com.kuang.repositories;

import com.kuang.pojo.Customer;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;


public interface CustomerQueryDSLRepository extends PagingAndSortingRepository<Customer, Long> , QuerydslPredicateExecutor<Customer> {




}

 测试类

package com.kuang.test;

import com.kuang.config.ApplicationConfig;
import com.kuang.pojo.Customer;
import com.kuang.pojo.QCustomer;
import com.kuang.repositories.CustomerQueryDSLRepository;
import com.kuang.repositories.CustomerRepository;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@ContextConfiguration(classes = ApplicationConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class QueryDslTest {

    @Autowired
    private CustomerQueryDSLRepository customerQueryDSLRepository;


    @Test
    public void name() {
        QCustomer customer = QCustomer.customer;

        //通过ID查找
        BooleanExpression eq = customer.custId.eq(5L);
        System.out.println(customerQueryDSLRepository.findOne(eq));

    }


    /**
     * 查询客户名称范围
     * id > 大于
     * 地址精确
     */
    @Test
    public void test02() {
        QCustomer customer = QCustomer.customer;

        BooleanExpression be = customer.custName.in("忽忽", "刘备")
                .and(customer.custId.gt(0L))
                .and(customer.custAddress.eq("杭州"));


        System.out.println(customerQueryDSLRepository.findOne(be));

    }
}

五、自定义操作-Specifications

package com.kuang.repositories;

import com.kuang.pojo.Customer;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;


public interface CustomerSpecificationsRepository extends PagingAndSortingRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {

}
package com.kuang.test;

import com.kuang.config.ApplicationConfig;
import com.kuang.pojo.Customer;
import com.kuang.repositories.CustomerRepository;
import com.kuang.repositories.CustomerSpecificationsRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.criteria.*;
import java.util.List;

@ContextConfiguration(classes = ApplicationConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpecificaTest {
    @Autowired
    private CustomerSpecificationsRepository repository;

    @Test
    public void name() {
        List<Customer> all = repository.findAll(new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                //root from   Customer //获取列
                // CriteriaBuilder  where 设置各种条件(> < in ..)
                //query 组合 (order by ,  where )


                return null;
            }
        });

    }


    /**
     * 查询客户范围(in)
     * id > 大于
     * 地址 精确
     */
    @Test
    public void select() {
        List<Customer> all = repository.findAll(new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //root from   Customer //获取列
                // CriteriaBuilder  where 设置各种条件(> < in ..)
                //query 组合 (order by ,  where )
                Path<Long> custID = root.get("custId");
                Path<String> custName = root.get("custName");
                Path<String> custAddress = root.get("custAddress");

                //参数1:为那个字段设置条件  参数2 :值
                Predicate custNameP = cb.equal(custName, "刘备");
                Predicate custIDP = cb.greaterThan(custID,0L);

                CriteriaBuilder.In<String> in = cb.in(custAddress);
                in.value("叙述").value("wangwu");
                Predicate and = cb.and(custIDP,custNameP,in);
                return and;
            }
        });
        System.out.println(all);

    }

    @Test
    public void dongtaiSQL() {
        Customer customer = new Customer();
        customer.setCustName("老六");
        customer.setCustId(0L);
        customer.setCustAddress("徐庶,王五");



    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1315874.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Linux上使用HTTP协议进行数据获取的实战示例

嗨&#xff0c;Linux爱好者们&#xff0c;今天我们要一起探讨一下如何在Linux上进行HTTP协议的数据获取。这不是一项简单的任务&#xff0c;但放心&#xff0c;我会以最简单的语言&#xff0c;结合实例来给大家讲解。 首先&#xff0c;我们需要一个工具&#xff0c;那就是curl…

Flutter工具安装与环境搭建

1、下载 Flutter SDK&#xff0c;下载完成后&#xff0c;在需要放置SDK的地方解压即可。 注意&#xff1a; 请勿将 Flutter 有特殊字符或空格的路径下。请勿将 Flutter 安装在需要高权限的文件夹内&#xff0c;例如 C:\Program Files\。 2、配置环境变量 例如&#xff1a; …

Java学习之线程锁

一、多线程 对于多线程的概念&#xff0c;其实很容易理解&#xff0c;之前我们的学习中无论多长或者怎样的代码&#xff0c;都是线性执行的&#xff0c;也就是很显而易见的自上而下执行&#xff0c;这也是所有语言中最常见的执行方式&#xff0c;那么这种执行方式有什么弊端呢…

CLEARTEXT communication not enabled for client

CLEARTEXT communication not enabled for client 把BaseHttpClient中的supportTsl修改为false

Python生成器(Generator)的应用场景和使用(继续更新...)

学习网页&#xff1a; Welcome to Python.orghttps://www.python.org/https://www.python.org/ Python生成器&#xff08;Generator&#xff09; 生成器在Python中有很多应用场景&#xff0c;以下是一些常见的应用场景&#xff1a; 处理大数据量和耗时操作的场景&#xff…

魔众文库系统v5.7.0版本文件顺序选择,短信注册支持设置密码,前端界面升级

文件顺序选择&#xff0c;短信注册支持设置密码&#xff0c;前端界面升级 [新功能] 富文本支持文档一键导入&#xff0c;支持Word文档&#xff08;docx&#xff09;、Markdown文档&#xff08;md&#xff09; [新功能] 财务中心→全部订单新增"业务订单ID"筛选条件…

C++相关闲碎记录(15)

1、string字符串 #include <iostream> #include <string> using namespace std;int main (int argc, char** argv) {const string delims(" \t,.;");string line;// for every line read successfullywhile (getline(cin,line)) {string::size_type beg…

布局前沿技术,紫光展锐推动6G创新融合发展

随着5G进入规模化商用阶段&#xff0c;6G研究已在全球范围内拉开帷幕。2023年6月&#xff0c;ITU发布了《IMT面向2030及未来发展的框架和总体目标建议书》&#xff0c;在升级5G三大应用场景的同时&#xff0c;扩展出三个跨领域场景&#xff0c;形成6G的六大应用场景&#xff0c…

读书心得(内容取自高质量C/C++编程)

版式虽然不会影响程序的功能&#xff0c;但会影响可读性。程序的版式追求清晰、美观&#xff0c;是 程序风格的重要构成因素。 可以把程序的版式比喻为“书法”。好的“书法”可让人对程序一目了然&#xff0c;看得兴致勃勃。差的程序“书法”如螃蟹爬行&#xff0c;让人看得…

C++实现简单的猜数字小游戏

猜数字 小游戏介绍&#xff1a;猜数字游戏是令游戏机随机产生一个100以内的正整数&#xff0c;用户输入一个数对其进行猜测&#xff0c;需要你编写程序自动对其与随机产生的被猜数进行比较&#xff0c;并提示大了&#xff0c;还是小了&#xff0c;相等表示猜到了。如果猜到&…

音频DAC,ADC,CODEC的选型分析,高性能立体声

想要让模拟信号和数字信号顺利“交往”&#xff0c;就需要一座像“鹊桥”一样的中介&#xff0c;将两种不同的语言转变成统一的语言&#xff0c;消除无语言障碍。这座鹊桥就是转换器芯片&#xff0c;也就是ADC芯片。ADC芯片的全称是Analog-to-Digital Converter, 即模拟数字转换…

TCPIP介绍

可见 TCP/IP 被分为 4 层&#xff0c;每层承担的任务不一样&#xff0c;各层的协议的工作方式也不一样&#xff0c;每层封装上层数据的方式也不一样&#xff1a; 应用层&#xff1a;应用程序通过这一层访问网络&#xff0c;常见 FTP、HTTP、DNS 和 TELNET 协议&#xff1b; 传输…

【C语言】详解文件操作

&#xff08;零&#xff09;引入 终端是计算机系统中与用户进行交互的界面。 在以往的程序中&#xff0c;我们通过终端用键盘输入数据&#xff0c;通过屏幕输出信息。 但是&#xff0c;如果我们不想手动低效地输入数据&#xff0c;而是通过文件一次性高效输入&#xff1b; 如果…

OpenHarmony 如何去除系统锁屏应用

前言 OpenHarmony源码版本&#xff1a;4.0release / 3.2 release 开发板&#xff1a;DAYU / rk3568 一、3.2版本去除锁屏应用 在源码根目录下&#xff1a;productdefine/common/inherit/rich.json 中删除screenlock_mgr组件的编译配置&#xff0c;在rich.json文件中搜索th…

GraphicsProfiler 使用教程

GraphicsProfiler 使用教程 1.工具简介&#xff1a;2.Navigation介绍2.1.打开安装好的Graphics Profiler。2.2.将手机连接到计算机&#xff0c;软件会在手机中安装一个GraphicsProfiler应用(该应用是无界面的&#xff09;。2.3.Show files list2.4.Record new trace2.4.1.Appli…

自然数分解 C语言xdoj64

输入说明 一个正整数 n&#xff0c;0<n<30 输出说明 输出n个连续奇数&#xff0c;数据之间用空格隔开&#xff0c;并换行 输入样例 4 输出样例 13 15 17 19 int main() {int n;scanf("%d",&n);if(n % 2 0){//n为偶数int in;//打印数字个数&#xff0c;做循…

【每日一题】统计区间中的整数数目

文章目录 Tag题目来源解题思路方法一&#xff1a;平衡二叉搜索树 写在最后 Tag 【平衡二叉搜索树】【设计类】【2023-12-16】 题目来源 2276. 统计区间中的整数数目 解题思路 方法一&#xff1a;平衡二叉搜索树 思路 用一棵平衡二叉搜索树维护插入的区间&#xff0c;树中的…

Java-----链表练习题(上)

本篇碎碎念&#xff1a;本篇无碎碎念 今日份励志文案: 很多人认为他们在思考&#xff0c;其实他们只是在整理自己的偏见 目录 一.203. 移除链表元素 - 力扣&#xff08;LeetCode&#xff09; 二.21. 合并两个有序链表 - 力扣&#xff08;LeetCode&#xff09…

【STM32入门】4.2对射红外传感器计次

1.接线方式 主要是编写传感器的驱动、配合OLED&#xff0c;每遮挡对射红外传感器&#xff0c;OLED屏幕的计数就加一。 2.驱动编写 首先新建.c文件和.h文件&#xff0c;命名为CountSensor 国际惯例&#xff0c;.c文件内要包含stm32.h头文件&#xff0c;然后编写 CountSensor_…

C++初阶-list类的模拟实现

list类的模拟实现 一、基本框架1.1 节点类1.2 迭代器类1.3 list类 二、构造函数和析构函数2.1 构造函数2.2 析构函数 三、operator的重载和拷贝构造3.1 operator的重载3.2 拷贝构造 四、迭代器的实现4.1 迭代器类中的各种操作4.1 list类中的迭代器 五、list的增容和删除5.1 尾插…