SpringJPA使用Specification对象实现动态查询+排序+分页

动态查询

 @Test
    public void findByPageAndSort() {
        //动态查询条件
        Customer customer = new Customer();
        //  customer.setCustName("%人%");
        // customer.setCustLevel("%仙人%");
        // customer.setCustPhone("23534");
        customer.setCustAddress("%村%");

        /**
         *   分页对象
         *   page:当前页码
         *   size:数据展示条数
         *   new Sort(): 排序对象
         *   Sort.Direction.Desc :倒叙排序
         *   properties: 排序字段 (custId)
         */
        Pageable pageable = new PageRequest(0, 2, new Sort(Sort.Direction.DESC, "custId"));

        Page pages = customerDao.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                if (customer == null) {
                    return null;
                }
                //创建条件集合
                ArrayList list = new ArrayList<>();
                if (customer.getCustId() != null && !customer.getCustId().equals("")) {
                    Predicate custId = cb.equal(root.get("custId"), customer.getCustId());
                    list.add(custId);
                }
                if (customer.getCustName() != null && !customer.getCustName().equals("")) {
                    list.add(cb.like(root.get("custName").as(String.class), customer.getCustName()));
                }
                if (customer.getCustSource() != null && !customer.getCustSource().equals("")) {
                    list.add(cb.like(root.get("custSource").as(String.class), customer.getCustSource()));
                }
                if (customer.getCustIndustry() != null && !customer.getCustIndustry().equals("")) {
                    list.add(cb.like(root.get("custIndustry").as(String.class), customer.getCustIndustry()));

                }
                if (customer.getCustLevel() != null && !customer.getCustLevel().equals("")) {
                    list.add(cb.like(root.get("custLevel").as(String.class), customer.getCustLevel()));
                }
                if (customer.getCustPhone() != null && !customer.getCustPhone().equals("")) {
                    list.add(cb.equal(root.get("custPhone"), customer.getCustPhone()));
                }
                if (customer.getCustAddress() != null && !customer.getCustAddress().equals("")) {
                    list.add(cb.like(root.get("custAddress").as(String.class), customer.getCustAddress()));
                }

                Predicate[] predicates = list.toArray(new Predicate[0]);
                //返回的必须是Predicate类型的数组,通过集合实现动态添加Predicate对象,转换为数组.
                return cb.and(predicates);
            }
        }, pageable);

        System.out.println("每页展示数据: ");
        for (Customer page : pages) {
            System.out.println(page);
        }
        System.out.println("查询出的总记录数: " + pages.getTotalElements());
        System.out.println("数据总页数: " + pages.getTotalPages());

    }

applicationContext.xml配置
注意事项:maven项目时,该配置文件目录必须放在resources/META-INF/applicationContext.xml




    

    
    
        
        
        
        
        
            
        

        
        
            
                
                
                
                
                
                
                
                
            
        

        
        
            
        

        
        
            
                update
            
        

    

    
    
        
        
        
        
    

    
    

    
    
        
    

    
    
        
            
            
            
            
            
            
            
        
    

    
    
        
        
    


    

    
    

Dao层接口,必须继承JpaRepository和JpaSpecificationExecutor
/**

  • JpaRepository<实体类类型,主键类型> 用来完成基本CRUD操作
  • JpaSpecificationExecutor<实体类类型> 用来完成复杂查询操作(分页)
    */
package com.qyf.dao;

import com.qyf.domain.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * JpaRepository<实体类类型,主键类型> 用来完成基本CRUD操作
 * JpaSpecificationExecutor<实体类类型> 用来完成复杂查询操作(分页)
 */
public interface CustomerDao extends JpaRepository, JpaSpecificationExecutor {
    /**
     * 根据用户名查询用户
     *
     * @param name
     * @return
     */
    @Query("from Customer  where custName = ?")
    public Customer findCustomerName(String name);

    /**
     * 根据用户名和ID查询用户
     *
     * @param id
     * @param name
     * @return
     */
    @Query("from Customer where custName = ?2 and custId = ?1")
    public Customer abc(@Param("b") Long id, @Param("a") String name);


    /**
     * 根据用户名和ID查询用户
     *
     * @param id
     * @param name
     * @return
     */
    @Query(value = "from Customer where custName = :a and custId =  :b")
    public Customer ddd(@Param("b") Long id, @Param("a") String name);


    /**
     * 使用原生SQL
     */

    @Query(value = "select * from cst_customer where cust_id = :id and cust_level = :level", nativeQuery = true)
    public Customer sqlTest(@Param("level")String level,@Param("id")Long id);


    /**
     * plsq模糊查询
     */
    @Query("from Customer where custName like  :n and custId= :d")
    public Customer likeQ(@Param("d")Long id,@Param("n")String name);

    /**
     * 模糊查询多个
     */
    @Query("from  Customer  where  custName like ?")
    public List findMore(String like);

    /**
     * 修改漩涡鸣人的等级
     */
    @Query(value = "update Customer set custLevel = ?1 where custId= ?2")
    @Modifying
    public void updateLevel(String level,Long id);

    /**
     * 做掉卡卡西
     */
    @Query(value = "delete from Customer where  custId = ?1")
    @Modifying
    public void skillKakaxi(Long id);


    public Customer findByCustNameAndCustAddress(String name,String address);

    public void deleteByCustIdAndCustAddress(Long id,String addr);
}

实体类对象

package com.qyf.domain;

import javax.persistence.*;
import java.io.Serializable;


@Entity //声明实体类
@Table(name = "cst_customer") //建立实体类和表的映射关系
public class Customer implements Serializable {

    @Id //声明当前私有属性为主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //配置主键的生成策略
    @Column(name = "cust_id")   //指定对象的属性映射表中的字段
    private Long custId;

    @Column(name = "cust_name")
    private String custName;

    @Column(name = "cust_source")
    private String custSource;

    @Column(name = "cust_industry")
    private String custIndustry;

    @Column(name = "cust_level")
    private String custLevel;

    @Column(name = "cust_phone")
    private String custPhone;

    @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 getCustSource() {
        return custSource;
    }

    public void setCustSource(String custSource) {
        this.custSource = custSource;
    }

    public String getCustIndustry() {
        return custIndustry;
    }

    public void setCustIndustry(String custIndustry) {
        this.custIndustry = custIndustry;
    }

    public String getCustLevel() {
        return custLevel;
    }

    public void setCustLevel(String custLevel) {
        this.custLevel = custLevel;
    }

    public String getCustAddress() {
        return custAddress;
    }

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

    public String getCustPhone() {
        return custPhone;
    }

    public void setCustPhone(String custPhone) {
        this.custPhone = custPhone;
    }

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


随手测试代码(可忽略)

package com.qyf.test;

import com.qyf.dao.CustomerDao;
import com.qyf.domain.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/applicationContext.xml")
public class CustomerTest {

    @Autowired
    private CustomerDao customerDao;

    /**
     * 添加功能
     */
    @Test
    public void testAdd() {
        Customer customer = new Customer();
        customer.setCustName("鼬");
        customerDao.save(customer);

    }

    /**
     * 修改
     */
    @Test
    public void testUpdate() {
        Customer one = customerDao.findOne(4L);
        one.setCustLevel("仙人");
        customerDao.save(one);

    }

    /**
     * 删除
     */
    @Test
    public void testdelete() {
        customerDao.delete(2L);

    }

    /**
     * 查询全部
     */
    @Test
    public void testFindAll() {
        List customers = customerDao.findAll();
        for (Customer customer : customers) {
            System.out.println(customer);
        }

    }

    /**
     * 根据用户名查询
     */
    @Test
    public void findOne() {
        Customer cus = customerDao.abc(4L, "漩涡鸣人");
        System.out.println(cus);

    }

    @Test
    public void findOne2() {
        Customer cus = customerDao.ddd(4L, "漩涡鸣人");
        System.out.println(cus);

    }

    @Test
    public void findOne3() {
        Customer cs = customerDao.sqlTest("仙人", 4L);
        System.out.println(cs);


    }

    @Test
    public void findOne4() {
        Customer cs = customerDao.likeQ(4L, "%人%");
        System.out.println(cs);


    }

    @Test
    public void findOne5() {
        List more = customerDao.findMore("%人%");
        for (Customer customer : more) {
            System.out.println(customer);
        }


    }


    @Test
    @Transactional
    @Rollback(value = false)
    public void findOne6() {
        customerDao.updateLevel("九尾", 4L);

    }


    @Test
    @Transactional
    @Rollback(value = false)
    public void findOne7() {
        customerDao.delete( 9L);

    }

    @Test
    public void test1(){

        Customer cs = customerDao.findByCustNameAndCustAddress("漩涡鸣人", "火影村");
        System.out.println(cs);
    }


    @Test
    @Transactional
    @Rollback(value = false)
    public void test2(){

        customerDao.deleteByCustIdAndCustAddress(10L,"三人组");
    }


}

你可能感兴趣的:(笔记)