当前位置: 首页 > 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进行渗透测…...

JavaSec-RCE

简介 RCE(Remote Code Execution)&#xff0c;可以分为:命令注入(Command Injection)、代码注入(Code Injection) 代码注入 1.漏洞场景&#xff1a;Groovy代码注入 Groovy是一种基于JVM的动态语言&#xff0c;语法简洁&#xff0c;支持闭包、动态类型和Java互操作性&#xff0c…...

css实现圆环展示百分比,根据值动态展示所占比例

代码如下 <view class""><view class"circle-chart"><view v-if"!!num" class"pie-item" :style"{background: conic-gradient(var(--one-color) 0%,#E9E6F1 ${num}%),}"></view><view v-else …...

【OSG学习笔记】Day 18: 碰撞检测与物理交互

物理引擎&#xff08;Physics Engine&#xff09; 物理引擎 是一种通过计算机模拟物理规律&#xff08;如力学、碰撞、重力、流体动力学等&#xff09;的软件工具或库。 它的核心目标是在虚拟环境中逼真地模拟物体的运动和交互&#xff0c;广泛应用于 游戏开发、动画制作、虚…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

可靠性+灵活性:电力载波技术在楼宇自控中的核心价值

可靠性灵活性&#xff1a;电力载波技术在楼宇自控中的核心价值 在智能楼宇的自动化控制中&#xff0c;电力载波技术&#xff08;PLC&#xff09;凭借其独特的优势&#xff0c;正成为构建高效、稳定、灵活系统的核心解决方案。它利用现有电力线路传输数据&#xff0c;无需额外布…...

Leetcode 3577. Count the Number of Computer Unlocking Permutations

Leetcode 3577. Count the Number of Computer Unlocking Permutations 1. 解题思路2. 代码实现 题目链接&#xff1a;3577. Count the Number of Computer Unlocking Permutations 1. 解题思路 这一题其实就是一个脑筋急转弯&#xff0c;要想要能够将所有的电脑解锁&#x…...

leetcodeSQL解题:3564. 季节性销售分析

leetcodeSQL解题&#xff1a;3564. 季节性销售分析 题目&#xff1a; 表&#xff1a;sales ---------------------- | Column Name | Type | ---------------------- | sale_id | int | | product_id | int | | sale_date | date | | quantity | int | | price | decimal | -…...

基于SpringBoot在线拍卖系统的设计和实现

摘 要 随着社会的发展&#xff0c;社会的各行各业都在利用信息化时代的优势。计算机的优势和普及使得各种信息系统的开发成为必需。 在线拍卖系统&#xff0c;主要的模块包括管理员&#xff1b;首页、个人中心、用户管理、商品类型管理、拍卖商品管理、历史竞拍管理、竞拍订单…...

MySQL 8.0 事务全面讲解

以下是一个结合两次回答的 MySQL 8.0 事务全面讲解&#xff0c;涵盖了事务的核心概念、操作示例、失败回滚、隔离级别、事务性 DDL 和 XA 事务等内容&#xff0c;并修正了查看隔离级别的命令。 MySQL 8.0 事务全面讲解 一、事务的核心概念&#xff08;ACID&#xff09; 事务是…...

​​企业大模型服务合规指南:深度解析备案与登记制度​​

伴随AI技术的爆炸式发展&#xff0c;尤其是大模型&#xff08;LLM&#xff09;在各行各业的深度应用和整合&#xff0c;企业利用AI技术提升效率、创新服务的步伐不断加快。无论是像DeepSeek这样的前沿技术提供者&#xff0c;还是积极拥抱AI转型的传统企业&#xff0c;在面向公众…...