springData JPA 的JPA简单的查询

我爱海鲸 2024-11-02 16:54:28 暂无标签

简介jpa、hibernate、springboot

queries要设置为resource(先使用maven构建)

1、SpringDataJPAConfig:

package xyz.haijin.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * jpa配置
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
//@Configuration          // 标记当前类为配置类   =xml配文件
@EnableJpaRepositories(basePackages="xyz.haijin.repositories")  // 启动jpa    <jpa:repositories
@EnableTransactionManagement    // 开启事务
public class SpringDataJPAConfig {

    /*
    *  <!--数据源-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" name="dataSource">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/springdata_jpa?characterEncoding=UTF-8"/>
    </bean>
    * */
    @Bean
    public DataSource dataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("haijinmysql");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.168.3.10:3306/springdata_jpa?characterEncoding=UTF-8");

        return  dataSource;

    }

    /*
    *  <!--EntityManagerFactory-->
    <bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <!--Hibernate实现-->
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--生成数据库表-->
                <property name="generateDdl" value="true"></property>
                <property name="showSql" value="true"></property>
            </bean>
        </property>
        <!--设置实体类的包-->
        <property name="packagesToScan" value="com.tuling.pojo"></property>
        <property name="dataSource" ref="dataSource" ></property>
    </bean>
    * */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("xyz.haijin.po");
        factory.setDataSource(dataSource());
        return factory;
    }

    /*
    * <bean class="org.springframework.orm.jpa.JpaTransactionManager" name="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>
    * */
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {

        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory);
        return txManager;
    }
}

2、Customer:

package xyz.haijin.po;

import javax.persistence.*;

/**
 * 客户表
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
@Entity     // 作为hibernate 实体类
@Table(name = "tb_customer")       // 映射的表明
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long custId; //客户的主键

    @Column(name = "cust_name")
    private String custName;//客户名称

    @Column(name="cust_address")
    private String custAddress;//客户地址

    public Long getCustId() {
        return custId;
    }

    public void setCustId(Long custId) {
        this.custId = custId;
    }

    public String getCustName() {
        return custName;
    }

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

    public String getCustAddress() {
        return custAddress;
    }

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

    @Override
    public String toString() {
        return "Customer{" +
                "custId=" + custId +
                ", custName='" + custName + '\'' +
                ", custAddress='" + custAddress + '\'' +
                "}\n";
    }

}

3、CustomerMethodNameRepository:

package xyz.haijin.repositories;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;
import xyz.haijin.po.Customer;

import java.util.List;

/**
 * 操作
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
public interface CustomerMethodNameRepository extends PagingAndSortingRepository<Customer,Long> {

    List<Customer> findByCustName(String custName);


    boolean existsByCustName(String custName);


    @Transactional
    @Modifying
    int deleteByCustId(Long custName);



    List<Customer> findByCustNameLike(String custName);

}

4、CustomerQBERepository:

package xyz.haijin.repositories;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;
import xyz.haijin.po.Customer;

/**
 * 操作
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
public interface CustomerQBERepository
        extends PagingAndSortingRepository<Customer,Long>
        , QueryByExampleExecutor<Customer> {



}

5、CustomerQueryDSLRepository:

package xyz.haijin.repositories;

import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import xyz.haijin.po.Customer;

/**
 * 操作
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
public interface CustomerQueryDSLRepository extends
        PagingAndSortingRepository<Customer,Long>
        , QuerydslPredicateExecutor<Customer> {

}

6、CustomerRepository:

package xyz.haijin.repositories;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import xyz.haijin.po.Customer;

import java.util.List;

/**
 * 操作
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
public interface CustomerRepository extends PagingAndSortingRepository<Customer,Long> {

    // 增删查改

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

    // 修改
    @Transactional
    @Modifying   // 通知springdatajpa 是增删改的操作
    @Query("UPDATE Customer c set c.custName=:custName where c.custId=:id")
    int updateCustomer(@Param("custName") String custName,@Param("id")Long id);


    @Transactional
    @Modifying   // 通知springdatajpa 是增删改的操作
    @Query("DELETE FROM Customer c where c.custId=?1")
    int deleteCustomer(Long id);

    // 新增  JPQL
    @Transactional
    @Modifying   // 通知springdatajpa 是增删改的操作
    @Query("INSERT INTO Customer (custName) SELECT c.custName FROM Customer c where c.custId=?1")
    int insertCustomerBySelect(Long id);


    @Query(value="select * FROM tb_customer where cust_name=:custName "
            ,nativeQuery = true)
    List<Customer> findCustomerByCustNameBySql(@Param("custName") String custName);

}

7、CustomerSpecificationsRepository:

package xyz.haijin.repositories;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import xyz.haijin.po.Customer;

/**
 * 操作
 * <p>
 * 2024/11/2.
 *
 * @author haijin
 * @version v1
 */
public interface CustomerSpecificationsRepository
        extends PagingAndSortingRepository<Customer,Long>,
        JpaSpecificationExecutor<Customer> {

}

8、spring.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:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa
    https://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--用于整合jpa  @EnableJpaRepositories -->
    <jpa:repositories base-package="xyz.haijin.repositories"
                      entity-manager-factory-ref="entityManagerFactory"
                      transaction-manager-ref="transactionManager"
    />


    <!--EntityManagerFactory-->
    <bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="jpaVendorAdapter">
            <!--Hibernate实现-->
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--生成数据库表-->
                <property name="generateDdl" value="true"></property>
                <property name="showSql" value="true"></property>
            </bean>
        </property>
        <!--设置实体类的包-->
        <property name="packagesToScan" value="xyz.haijin.po"></property>
        <property name="dataSource" ref="dataSource" ></property>
    </bean>

    <!--数据源-->
    <bean class="com.alibaba.druid.pool.DruidDataSource" name="dataSource">
        <property name="username" value="root"/>
        <property name="password" value="haijinmysql"/>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.3.10:3306/springdata_jpa?characterEncoding=UTF-8"/>
    </bean>

    <!--声明式事务-->
    <bean class="org.springframework.orm.jpa.JpaTransactionManager" name="transactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"></property>
    </bean>

    <!--启动注解方式的声明式事务-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>

9、JpqlTest:

package xyz.haijin;

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 xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerRepository;

import java.util.List;

@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class JpqlTest {

    // jdk动态代理的实例
    @Autowired
    CustomerRepository repository;

    @Test
    public  void testR(){
        List<Customer> customer = repository.findCustomerByCustName("李四");
        System.out.println(customer);
    }

    @Test
    public  void testU(){
        int result = repository.updateCustomer("王五", 7L);
        System.out.println(result);
    }

    @Test
    public  void testD(){
        int result = repository.deleteCustomer(10L);
        System.out.println(result);
    }

    @Test
    public  void testC(){
        int result = repository.insertCustomerBySelect(7L);
        System.out.println(result);
    }

    @Test
    public  void testR_sql(){
        List<Customer> customer = repository.findCustomerByCustNameBySql("haijin");
        System.out.println(customer);

    }


}

10、MethodNameTest:

package xyz.haijin;

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 xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerMethodNameRepository;

import java.util.List;


@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MethodNameTest {

    // jdk动态代理的实例
    @Autowired
    CustomerMethodNameRepository repository;

    @Test
    public  void test01() {
        List<Customer> list = repository.findByCustName("李四");
        System.out.println(list);
    }

    @Test
    public  void test02() {
        boolean exists = repository.existsByCustName("xxx");
        System.out.println(exists);
    }

    @Test
    public  void test03() {
        int exists = repository.deleteByCustId(12L);
        System.out.println(exists);
    }


    @Test
    public  void test04() {
        List<Customer> list = repository.findByCustNameLike("徐%");
        System.out.println(list);
    }
}

11、QBETest:

package xyz.haijin;

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 xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerQBERepository;

import java.util.List;


@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class QBETest {

    // jdk动态代理的实例
    @Autowired
    CustomerQBERepository repository;

    /**
     * 简单实例  客户名称  客户地址动态查询
     */
    @Test
    public  void test01(){

        // 查询条件
        Customer customer=new Customer();
        customer.setCustName("haijin");
        customer.setCustAddress("BEIJING");

        // 通过Example构建查询条件
        Example<Customer> example = Example.of(customer);

        List<Customer> list = (List<Customer>) repository.findAll(example);
        System.out.println(list);
    }


    /**
     *  通过匹配器 进行条件的限制
     * 简单实例  客户名称  客户地址动态查询
     */
    @Test
    public  void test02(){

        // 查询条件
        Customer customer=new Customer();
        customer.setCustName("jin");
        customer.setCustAddress("JING");

        // 通过匹配器 对条件行为进行设置
        ExampleMatcher matcher = ExampleMatcher.matching()
                //.withIgnorePaths("custName")       // 设置忽略的属性
                //.withIgnoreCase("custAddress")      // 设置忽略大小写
                //.withStringMatcher(ExampleMatcher.StringMatcher.ENDING);    // 对所有条件字符串进行了结尾匹配
                .withMatcher("custAddress",m -> m.endsWith().ignoreCase());      // 针对单个条件进行限制, 会使withIgnoreCase失效,需要单独设置
                //.withMatcher("custAddress", ExampleMatcher.GenericPropertyMatchers.endsWith().ignoreCase());

        // 通过Example构建查询条件
        Example<Customer> example = Example.of(customer,matcher);

        List<Customer> list = (List<Customer>) repository.findAll(example);
        System.out.println(list);
    }
}

12、QueryDSLTest:

package xyz.haijin;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
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 org.springframework.util.StringUtils;
import xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.po.QCustomer;
import xyz.haijin.repositories.CustomerQueryDSLRepository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;


@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class QueryDSLTest {

    // jdk动态代理的实例
    @Autowired
    CustomerQueryDSLRepository repository;

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

        // 通过Id查找
        BooleanExpression eq = customer.custId.eq(1L);

        System.out.println(repository.findOne(eq));

    }


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

        // 通过Id查找
        BooleanExpression and = customer.custName.in("haijin", "王五")
                .and(customer.custId.gt(0L))
                .and(customer.custAddress.eq("BEIJING"));

        System.out.println(repository.findOne(and));

    }

    /**
     * 查询客户名称范围 (in)
     * id  >大于
     * 地址  精确
     */
    @Test
    public  void test03() {

        Customer params=new Customer();
        params.setCustAddress("BEIJING");
        params.setCustId(0L);
        params.setCustName("haijin,王五");


        QCustomer customer = QCustomer.customer;

        // 初始条件 类似于1=1 永远都成立的条件
        BooleanExpression expression = customer.isNotNull().or(customer.isNull());

        expression=params.getCustId()>-1?
                expression.and(customer.custId.gt(params.getCustId())):expression;
        expression=!StringUtils.isEmpty( params.getCustName())?
                expression.and(customer.custName.in(params.getCustName().split(","))):expression;
        expression=!StringUtils.isEmpty( params.getCustAddress())?
                expression.and(customer.custAddress.eq(params.getCustAddress())):expression;


        System.out.println(repository.findAll(expression));

    }


    // 解决线程安全问题
    @PersistenceContext
    EntityManager em;

    /**
     * 自定义列查询、分组
     * 需要使用原生态的方式(Specification)
     * 通过Repository进行查询, 列、表都是固定
     */
    @Test
    public  void test04() {
        JPAQueryFactory factory = new JPAQueryFactory(em);

        QCustomer customer = QCustomer.customer;

        // 构建基于QueryDSL的查询
        JPAQuery<Tuple> tupleJPAQuery = factory.select(customer.custId, customer.custName)
                .from(customer)
                .where(customer.custId.eq(1L))
                .orderBy(customer.custId.desc());

        // 执行查询
        List<Tuple> fetch = tupleJPAQuery.fetch();

        // 处理返回数据
        for (Tuple tuple : fetch) {
            System.out.println(tuple.get(customer.custId));
            System.out.println(tuple.get(customer.custName));
        }

    }


    @Test
    public  void test05() {
        JPAQueryFactory factory = new JPAQueryFactory(em);
        QCustomer customer = QCustomer.customer;

        // 构建基于QueryDSL的查询
        JPAQuery<Long> longJPAQuery = factory.select(
                        customer.custId.sum())
                .from(customer)
                //.where(customer.custId.eq(1L))
                .orderBy(customer.custId.desc());

        // 执行查询
        List<Long> fetch = longJPAQuery.fetch();

        // 处理返回数据
        for (Long sum : fetch) {
            System.out.println(sum);
        }

    }
}

13、SpecificationTest:

package xyz.haijin;

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 org.springframework.util.StringUtils;
import xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerSpecificationsRepository;

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

@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpecificationTest {

    // jdk动态代理的实例
    @Autowired
    CustomerSpecificationsRepository repository;

    @Test
    public  void testR(){

        List<Customer> customer = 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)



                return null;
            }
        });

        System.out.println(customer);
    }


    /**
     * 查询客户范围 (in)
     * id  >大于
     * 地址  精确
     */
    @Test
    public  void testR2(){

        List<Customer> customer = 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<Object> custId = root.get("custId");
                Path<Object> custName = root.get("custName");
                Path<Object> custAddress = root.get("custAddress");

                // 参数1 :为哪个字段设置条件   参数2:值
                Predicate predicate = cb.equal(custAddress, "BEIJING");

                return predicate;
            }
        });

        System.out.println(customer);
    }


    /**
     * 查询客户范围 (in)
     * id  >大于
     * 地址  精确
     */
    @Test
    public  void testR3(){

        List<Customer> customer = 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 custAddressP = cb.equal(custAddress, "BEIJING");
                Predicate custIdP = cb.greaterThan(custId, 0L);
                CriteriaBuilder.In<String> in = cb.in(custName);
                in.value("haijin").value("王五");


                Predicate and = cb.and(custAddressP, custIdP,in);



                return and;
            }
        });

        System.out.println(customer);
    }


    /**
     * 查询客户范围 (in)
     * id  >大于
     * 地址  精确
     */
    @Test
    public  void testR4(){

        Customer params=new Customer();
        //params.setCustAddress("BEIJING");
        params.setCustId(0L);
        params.setCustName("haijin,王五");

        List<Customer> customer = 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)

                // 1. 通过root拿到需要设置条件的字段
                Path<Long> custId = root.get("custId");
                Path<String> custName = root.get("custName");
                Path<String> custAddress = root.get("custAddress");

                // 2. 通过CriteriaBuilder设置不同类型条件
                List<Predicate> list=new ArrayList<>();
                if(!StringUtils.isEmpty(params.getCustAddress())) {
                    // 参数1 :为哪个字段设置条件   参数2:值
                    list.add(cb.equal(custAddress, "BEIJING")) ;
                }
                if(params.getCustId()>-1){
                    list.add(cb.greaterThan(custId, 0L));
                }

                if(!StringUtils.isEmpty(params.getCustName())) {
                    CriteriaBuilder.In<String> in = cb.in(custName);
                    in.value("haijin").value("王五");
                    list.add(in);
                }


                // 组合条件
                Predicate and = cb.and(list.toArray(new Predicate[list.size()]));

                return and;
            }
        });

        System.out.println(customer);
    }


    @Test
    public  void testR5(){

        Customer params=new Customer();
        //params.setCustAddress("BEIJING");
        params.setCustId(0L);
        params.setCustName("haijin,王五");

        List<Customer> customer = 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:值
                List<Predicate> list=new ArrayList<>();
                if(!StringUtils.isEmpty(params.getCustAddress())) {
                    list.add(cb.equal(custAddress, "BEIJING")) ;
                }
                if(params.getCustId()>-1){
                    list.add(cb.greaterThan(custId, 0L));
                }

                if(!StringUtils.isEmpty(params.getCustName())) {
                    CriteriaBuilder.In<String> in = cb.in(custName);
                    in.value("haijin").value("王五");
                    list.add(in);
                }


                Predicate and = cb.and(list.toArray(new Predicate[list.size()]));

                Order desc = cb.desc(custId);

                return query.where(and).orderBy(desc).getRestriction();
            }
        });

        System.out.println(customer);
    }
}

14、SpringDataJpaPagingAndSortTest:

package xyz.haijin;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerRepository;


@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringDataJpaPagingAndSortTest
{
    // jdk动态代理的实例
    @Autowired
    CustomerRepository repository;

    @Test
    public  void testPaging(){
        Page<Customer> all = repository.findAll(PageRequest.of(0, 2));
        System.out.println(all.getTotalPages());
        System.out.println(all.getTotalElements());
        System.out.println(all.getContent());

    }

    @Test
    public  void testSort(){

        Sort sort = Sort.by("custId").descending();

        Iterable<Customer> all = repository.findAll(sort);

        System.out.println(all);

    }


    @Test
    public  void testSortTypeSafe(){

        Sort.TypedSort<Customer> sortType = Sort.sort(Customer.class);

        Sort sort = sortType.by(Customer::getCustId).descending();


        Iterable<Customer> all = repository.findAll(sort);

        System.out.println(all);

    }
}

15、SpringdataJpaTest:

package xyz.haijin;

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 xyz.haijin.config.SpringDataJPAConfig;
import xyz.haijin.po.Customer;
import xyz.haijin.repositories.CustomerRepository;

import java.util.Arrays;
import java.util.Optional;


// 基于junit4 spring单元测试
//@ContextConfiguration("/spring.xml")
@ContextConfiguration(classes = SpringDataJPAConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringdataJpaTest {

    // jdk动态代理的实例
    @Autowired
    CustomerRepository repository;

    @Test
    public  void testR(){
        Optional<Customer> byId = repository.findById(20L);

        System.out.println(byId.orElse(null));
    }

    @Test
    public  void testC(){


        Customer customer = new Customer();
        customer.setCustName("李四");

        System.out.println(repository.save(customer));
    }

    @Test
    public  void testD(){


        Customer customer = new Customer();
        customer.setCustId(3L);
        customer.setCustName("李四");

        repository.delete(customer);
    }


    @Test
    public  void testFindAll(){


        Iterable<Customer> allById = repository.findAllById(Arrays.asList(1L, 7L, 8L));

        System.out.println(allById);
    }

}

16、项目的pom:

<?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>springDataTest</artifactId>
        <groupId>xyz.haijin</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>springdata_jpa_02</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>

        <!-- junit4 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <!-- hibernate对jpa的支持包 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.32.Final</version>
        </dependency>

        <!-- Mysql and MariaDB -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </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 -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>${querydsl.version}</version>
        </dependency>

    </dependencies>

    <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>

17、全局pom:

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>xyz.haijin</groupId>
    <artifactId>springDataTest</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <modules>
        <module>jpa_hibernate_01</module>
        <module>springdata_jpa_02</module>
    </modules>

    <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>
        <mysql.version>8.0.29</mysql.version>
    </properties>


    <!--统一管理SpringData子项目的版本-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-bom</artifactId>
                <version>2021.1.0</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>



</project>

你好:我的2025