SpringData自定义操作

2023-12-16 23:20
文章标签 自定义 操作 springdata

本文主要是介绍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自定义操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/502264

相关文章

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

MySQL追踪数据库表更新操作来源的全面指南

《MySQL追踪数据库表更新操作来源的全面指南》本文将以一个具体问题为例,如何监测哪个IP来源对数据库表statistics_test进行了UPDATE操作,文内探讨了多种方法,并提供了详细的代码... 目录引言1. 为什么需要监控数据库更新操作2. 方法1:启用数据库审计日志(1)mysql/mariad

springboot如何通过http动态操作xxl-job任务

《springboot如何通过http动态操作xxl-job任务》:本文主要介绍springboot如何通过http动态操作xxl-job任务的问题,具有很好的参考价值,希望对大家有所帮助,如有错... 目录springboot通过http动态操作xxl-job任务一、maven依赖二、配置文件三、xxl-

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

一文详解Java Stream的sorted自定义排序

《一文详解JavaStream的sorted自定义排序》Javastream中的sorted方法是用于对流中的元素进行排序的方法,它可以接受一个comparator参数,用于指定排序规则,sorte... 目录一、sorted 操作的基础原理二、自定义排序的实现方式1. Comparator 接口的 Lam

Oracle 数据库数据操作如何精通 INSERT, UPDATE, DELETE

《Oracle数据库数据操作如何精通INSERT,UPDATE,DELETE》在Oracle数据库中,对表内数据进行增加、修改和删除操作是通过数据操作语言来完成的,下面给大家介绍Oracle数... 目录思维导图一、插入数据 (INSERT)1.1 插入单行数据,指定所有列的值语法:1.2 插入单行数据,指

SQL中JOIN操作的条件使用总结与实践

《SQL中JOIN操作的条件使用总结与实践》在SQL查询中,JOIN操作是多表关联的核心工具,本文将从原理,场景和最佳实践三个方面总结JOIN条件的使用规则,希望可以帮助开发者精准控制查询逻辑... 目录一、ON与WHERE的本质区别二、场景化条件使用规则三、最佳实践建议1.优先使用ON条件2.WHERE用

Linux链表操作方式

《Linux链表操作方式》:本文主要介绍Linux链表操作方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、链表基础概念与内核链表优势二、内核链表结构与宏解析三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势六、典型应用场景七、调试技巧与