当前位置: 首页 > news >正文

SpringData自定义操作

一、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 {@Autowiredprivate CustomerQueryByExampleRepository repository;@Testpublic 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);}/*** 通过匹配器 进行条件的限制* 简单实例 客户名称 客户地址动态查询**/@Testpublic 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 {@Autowiredprivate CustomerQueryDSLRepository customerQueryDSLRepository;@Testpublic void name() {QCustomer customer = QCustomer.customer;//通过ID查找BooleanExpression eq = customer.custId.eq(5L);System.out.println(customerQueryDSLRepository.findOne(eq));}/*** 查询客户名称范围* id > 大于* 地址精确*/@Testpublic 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 {@Autowiredprivate CustomerSpecificationsRepository repository;@Testpublic void name() {List<Customer> all = repository.findAll(new Specification<Customer>() {@Overridepublic Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {//root from   Customer //获取列// CriteriaBuilder  where 设置各种条件(> < in ..)//query 组合 (order by ,  where )return null;}});}/*** 查询客户范围(in)* id > 大于* 地址 精确*/@Testpublic void select() {List<Customer> all = repository.findAll(new Specification<Customer>() {@Overridepublic 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);}@Testpublic void dongtaiSQL() {Customer customer = new Customer();customer.setCustName("老六");customer.setCustId(0L);customer.setCustAddress("徐庶,王五");}
}

相关文章:

SpringData自定义操作

一、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.PagingAndSortingR…...

【Java JVM】运行时数据区

JVM 在执行 Java 程序的过程中会把它管理的内存分为若干个不同的数据区域, 这些区域有着各自的用途。 根据《Java虚拟机规范》中规定, JVM 所管理的内存大致包括以下几个运行时数据区域, 如图所示: 这个运行时数据区被分为了 5 大块 方法区 (Method Area)堆 (Heap)虚拟机栈 (V…...

k8s中pod监控数据在grafana中展示

实现目标:将kubesphere[K8S]中运行的pod监控数据在grafana平台进行展示。 前提说明:需要在k8s每个集群中内置的prometheus配置中将pod指标数据远程写入到victoriametrics持久化数据库中。 实现效果如下: CPU使用量: round(sum by (namespace, pod) (irate(container_cpu…...

人机协同之间也有混馈机制

不懂数学的狮子&#xff0c;能精准的在最佳时刻、最佳路径捕捉到羚羊&#xff0c;这种天赋的“算计”能力&#xff0c;可谓叹为观止&#xff01;里面既有反馈也有前馈&#xff0c;应该是混馈机制。混馈机制是指信息在系统中同时进行正向和反向的传递与调节。在狮子捕捉羚羊的过…...

微服务网关Gateway

springcloud官方提供的网关组件spring-cloud-starter-gateway,看pom.xml文件,引入了webflux做响应式编程,请求转发用到了netty的reactor模型,支持的请求数在1W~1.5W左右。hystrix停止维护后,官方推荐resilience4j做服务熔断,网关这里也能看到依赖。 对于网关提供的功能…...

flume:Ncat: Connection refused.

一&#xff1a;nc -lk 44444 和 nc localhost 44444区别 nc -lk 44444 和 nc localhost 44444 是使用 nc 命令进行网络通信时的两种不同方式。 1. nc -lk 44444&#xff1a; - 这个命令表示在本地监听指定端口&#xff08;44444&#xff09;并接受传入的连接。 - -l 选项…...

selenium 与 chromedriver安装

本文章向大家介绍selenium 安装与 chromedriver安装&#xff0c;主要包括selenium 安装与 chromedriver安装使用实例、应用技巧、基本知识点总结和需要注意事项供大家参考。 一、安装selenium 1、Selenium简介 Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开…...

【Unity】2D项目中如何让Camera展示的大小正好等于某一个Game Object的大小

【背景】 用Unity做工具软件的话希望Camera大小正好和界面Panel一致。 【方法一:手动调整】 相机设置成正交后手动调整边框,当然这种方法精确度不高。 【方法二:在Camera上追加如下脚本】 这里面的public变量里面拖放你想要对齐的目标对象即可。 using UnityEngine;pu…...

last block incomplete in decryption

测试AES加密参数时报出的错&#xff0c;对比参数&#xff0c;发现接口收到的请求参数少了个号。这是因为号在URL中是一个特殊字符&#xff0c;所以传递时可能会丢失。 处理方案 使用param.replaceAll(" ", "")统一替换空格为号。前端传递参数时&#xff0c…...

Guardrails for Amazon Bedrock 基于具体使用案例与负责任 AI 政策实现定制式安全保障(预览版)

作为负责任的人工智能&#xff08;AI&#xff09;战略的一部分&#xff0c;您现在可以使用 Guardrails for Amazon Bedrock&#xff08;预览版&#xff09;&#xff0c;实施专为您的用例和负责任的人工智能政策而定制的保障措施&#xff0c;以此促进用户与生成式人工智能应用程…...

flutter学习-day12-可滚动组件和监听

&#x1f4da; 目录 简介可滚动组件 SingleChildScrollViewListView separated分割线无限加载列表带标题列表 滚动监听和控制 ScrollController滚动监听NotificationListener滚动监听 AnimatedList动画列表滚动网格布局GridView 横轴子元素为固定数量横轴子元素为固定最大长度…...

LeetCode:967连续查相同的数字(DFS)

题目 返回所有长度为 n 且满足其每两个连续位上的数字之间的差的绝对值为 k 的 非负整数 。 请注意&#xff0c;除了 数字 0 本身之外&#xff0c;答案中的每个数字都 不能 有前导零。例如&#xff0c;01 有一个前导零&#xff0c;所以是无效的&#xff1b;但 0 是有效的。 …...

深入剖析NPM: Node包管理器的介绍和使用指南

导言&#xff1a;NPM&#xff08;Node Package Manager&#xff09;是JavaScript世界中最受欢迎的包管理器之一。它的出现大大简化了JavaScript开发过程中的依赖管理和模块化。本文将向您介绍NPM的基本概念、功能和常见用法&#xff0c;并为您提供一份详尽的NPM使用指南。 一、…...

AI视频-stable-video-diffusio介绍

介绍 stbilityai/stable-video-diffusion-img2vid-xt模型&#xff0c;由Stability AI开发和训练的基于散度的图像到视频生成模型。该模型可以接受一张静态图像作为条件,并生成出一个短视频。 该模型通过在SVD Image-to-Video [14帧]的基础上进行微调而来,可以生成576x1024分辨…...

day01-报表技术POI

前言 报表[forms for reporting to the higher organizations]&#xff0c;就是向上级报告情况的表格。简单的说&#xff1a;报表就是用表格、图表等格式来动态显示数据&#xff0c;可以用公式表示为&#xff1a;“报表 多样的格式 动态的数据”。 1、开发环境搭建 功能说…...

如何预防最新的.locked、.locked1勒索病毒感染您的计算机?

尊敬的读者&#xff1a; 近期&#xff0c;网络安全领域迎来一股新潮——.locked、.locked1勒索病毒的威胁&#xff0c;其先进的加密技术令人生畏。本文将深入剖析.locked、.locked1勒索病毒的阴谋&#xff0c;提供特色数据恢复策略&#xff0c;并揭示锁定恶劣行径的先锋预防手…...

实现两张图片的接缝线拼接

使用ORB算法检测特征点&#xff0c;并通过BFMatcher进行特征点匹配。然后&#xff0c;根据Lowes ratio test选择好的匹配点&#xff0c;并使用findHomography计算单应性矩阵。最后&#xff0c;使用warpPerspective将图像进行透视变换&#xff0c;然后将第二张图像粘贴到变换后的…...

基于JNI 实现 嵌套 List 类型参数解析

基于JNI 实现 嵌套 List 类型参数解析 背景分析解决 背景 在前面两篇文章中&#xff0c;我们总结了Java 调用 C/C SDK 的几种方案&#xff0c;分享了JNI在实践过程中的一些踩坑点&#xff0c;而在这篇文章将继续分享针对Java List类型及其嵌套类型&#xff0c;我们的JNI如何接…...

探索灵活性与可维护性的利器:策略(Strategy)模式详解

目录 ​编辑 1. 策略模式概述&#xff1a; 2. 主要角色&#xff1a; 3. 实例场景&#xff1a; 4. 具体实现步骤&#xff1a; 步骤一&#xff1a;定义策略接口 5. 使用策略模式的客户端代码&#xff1a; 总结&#xff1a; 我的其他博客 1. 策略模式概述&#xff1a; 策…...

压缩包文件暴力破解 -Server2005(解析)

任务五十一: 压缩包文件暴力破解 任务环境说明:Server2005 1. 通过本地PC中渗透测试平台Kali使用Nmap扫描目标靶机服务版本信息,将 Telnet 版本信息字符串 作为 Flag 提交; flag:Microsoft Windows XP telnetd 2. 通过本地PC中渗透测试平台Kali对服务器场景Windows进行渗透测…...

利用最小二乘法找圆心和半径

#include <iostream> #include <vector> #include <cmath> #include <Eigen/Dense> // 需安装Eigen库用于矩阵运算 // 定义点结构 struct Point { double x, y; Point(double x_, double y_) : x(x_), y(y_) {} }; // 最小二乘法求圆心和半径 …...

【Java学习笔记】Arrays类

Arrays 类 1. 导入包&#xff1a;import java.util.Arrays 2. 常用方法一览表 方法描述Arrays.toString()返回数组的字符串形式Arrays.sort()排序&#xff08;自然排序和定制排序&#xff09;Arrays.binarySearch()通过二分搜索法进行查找&#xff08;前提&#xff1a;数组是…...

【SpringBoot】100、SpringBoot中使用自定义注解+AOP实现参数自动解密

在实际项目中,用户注册、登录、修改密码等操作,都涉及到参数传输安全问题。所以我们需要在前端对账户、密码等敏感信息加密传输,在后端接收到数据后能自动解密。 1、引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId...

条件运算符

C中的三目运算符&#xff08;也称条件运算符&#xff0c;英文&#xff1a;ternary operator&#xff09;是一种简洁的条件选择语句&#xff0c;语法如下&#xff1a; 条件表达式 ? 表达式1 : 表达式2• 如果“条件表达式”为true&#xff0c;则整个表达式的结果为“表达式1”…...

【SQL学习笔记1】增删改查+多表连接全解析(内附SQL免费在线练习工具)

可以使用Sqliteviz这个网站免费编写sql语句&#xff0c;它能够让用户直接在浏览器内练习SQL的语法&#xff0c;不需要安装任何软件。 链接如下&#xff1a; sqliteviz 注意&#xff1a; 在转写SQL语法时&#xff0c;关键字之间有一个特定的顺序&#xff0c;这个顺序会影响到…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

NFT模式:数字资产确权与链游经济系统构建

NFT模式&#xff1a;数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新&#xff1a;构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议&#xff1a;基于LayerZero协议实现以太坊、Solana等公链资产互通&#xff0c;通过零知…...

【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分

一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计&#xff0c;提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合&#xff1a;各模块职责清晰&#xff0c;便于独立开发…...

在WSL2的Ubuntu镜像中安装Docker

Docker官网链接: https://docs.docker.com/engine/install/ubuntu/ 1、运行以下命令卸载所有冲突的软件包&#xff1a; for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do sudo apt-get remove $pkg; done2、设置Docker…...

NXP S32K146 T-Box 携手 SD NAND(贴片式TF卡):驱动汽车智能革新的黄金组合

在汽车智能化的汹涌浪潮中&#xff0c;车辆不再仅仅是传统的交通工具&#xff0c;而是逐步演变为高度智能的移动终端。这一转变的核心支撑&#xff0c;来自于车内关键技术的深度融合与协同创新。车载远程信息处理盒&#xff08;T-Box&#xff09;方案&#xff1a;NXP S32K146 与…...