Spring+SpringDataJpa集成

为了以后代码的扩展,每一层都需要创建一个父类,即便是此事父类中没有任何代码

applicationContest.xml 关键配置

Spring+SpringDataJpa集成_第1张图片


domain层:

 父类:BaseEmployee

package com.sunwei.domain;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public class BaseEmployee {
    @Id
    @GeneratedValue
    protected Long id;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @Override
    public String toString() {
        return "BaseEmployee{" +
                "id=" + id +
                '}';
    }
}

子类:Employee

package com.sunwei.domain;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="employee")
public class Employee extends BaseEmployee{
    private String username;
    private String password;
    private String email;
    private Integer age;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}

repository/dao层

package com.sunwei.repository;

import com.sun.org.apache.bcel.internal.generic.Select;
import com.sunwei.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface EmployeeRepository extends JpaRepository,JpaSpecificationExecutor{
    //根据名称进行查询
    Employee findByUsername(String username);
    //模糊查询
    List findByUsernameLike(String username);
    //多个条件查询
    List findByUsernameLikeAndEmailLike(String username,String email);
    //使用jpql查询
    @Query("Select o from Employee o where o.username=?1")
    Employee query01(String username);
    //jpql 模糊查询
    @Query("select o from Employee o  where   o.username like ?1 and  o.email like ?2")
    List query02(String username,String email);
    //原生sql
    @Query(nativeQuery = true,value = "SELECT * from employee where username=?")
    Employee query03(String username);    
}

抽取的功能层query:

父类 BaseQuery:

package com.sunwei.query;


import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
/*
* 父类抽取的特点
* 1.减少代码量
* 2.规范代码
* 3.保持扩展的灵活性
* */
public abstract class BaseQuery {
    //分页 当前页
    private int currentPage=1;
    //每页条数
    private int pageSize=10;
    //排序的字段名(如果前台没有传字段,代表不需要做排序)
    private  String orderName;
    //排序的规则
    private String orderType="ASC";
    //写个抽象方法去规范子类获取Specfication对象的名称必须叫:createSpec
    public abstract Specification createSpec();
    //创建排序对象
    public Sort CreateSort(){
        if(StringUtils.isNotBlank(orderName)){
            return new Sort(Sort.Direction.valueOf(orderType.toUpperCase()),orderName);
        }
        return null;
    }
    public int getCurrentPage() {
        return currentPage;
    }
    //第一页从0开始计算
    public int getJpaCurrentPage() {
        return currentPage-1;
    }
    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public String getOrderName() {
        return orderName;
    }
    public void setOrderName(String orderName) {
        this.orderName = orderName;
    }
    public String getOrderType() {
        return orderType;
    }
    public void setOrderType(String orderType) {
        this.orderType = orderType;
    }
}

子类EmployeeQuery

package com.sunwei.query;

import com.github.wenhao.jpa.Specifications;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;
/*
* 只用于employee的查询条件
* */
public class EmployeeQuery extends BaseQuery{
    private String username;
    private String email;
    private Integer age;
    //返回查询条件 where username=?
    @Override
    public Specification createSpec() {
        /**
         * like方法两个参数
         *  1.查询的字段
         *  2.这个字段条件对应的值
         * like方法三个参数
         *  1.boolean false,这个查询不执行
         *  2.查询的字段
         *  3.这个字段条件对应的值
         */
        Specification spec=Specifications.and()
                .like(StringUtils.isNoneBlank(username),"username","%"+username+"%")
                .like(StringUtils.isNoneBlank(email),"email","%"+email+"%")
                .gt(age!=null,"age",age)
                .build();
        return spec;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

 

Test层:

package com.sunwei.repository;

import com.github.wenhao.jpa.Specifications;
import com.sunwei.domain.Employee;

import com.sunwei.query.EmployeeQuery;
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.Pageable;
import org.springframework.data.domain.Sort;

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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class EmployeeTest {
    @Autowired
    private EmployeeRepository employeeRepository;
    //查询全部数据
    @Test
    public void testFindAll()throws Exception{

        List list = employeeRepository.findAll();
        list.forEach(e-> System.out.println(e));

    }
    //查询一条数据
    @Test
    public void testFindOne()throws Exception{
        Employee one = employeeRepository.findOne(247L);
        System.out.println(one);

    }
    //添加数据
    @Test
    public void testSave()throws Exception{
        Employee employee = new Employee();
        employee.setUsername("小芳");
        employee.setPassword("123456");
        employee.setAge(12);
        employee.setEmail("[email protected]");

        employeeRepository.save(employee);

    }
    //修改数据
    @Test
    public void testUpdate()throws Exception{
        Employee employee = new Employee();
        employee.setId(274L);
        employee.setUsername("小白");
        employee.setPassword("123456");
        employee.setAge(12);
        employee.setEmail("[email protected]");
        employeeRepository.save(employee);
    }
    //删除数据
    @Test
    public void testDelete()throws Exception{
        employeeRepository.delete(275L);
    }
    //得到数据总条数
    @Test
    public void testCount()throws Exception{
         System.out.println(employeeRepository.count());
    }
    /*=============================分页排序=================================*/
    //分页查询
    @Test
    public void testPage()throws Exception{
        //创建分页对象page
        Pageable pageable = new PageRequest(0, 8);
        Page page = employeeRepository.findAll(pageable);
        page.forEach(e-> System.out.println(e));
        System.out.println(page.getTotalElements()); //总条数
        System.out.println(page.getTotalPages()); //总页数
        System.out.println(page.getContent()); //当前页数据
        System.out.println(page.getNumber()); //第几页
        System.out.println(page.getNumberOfElements()); //当前页有多少个数据
        System.out.println(page.getSize()); //每页条数

    }

     //排序功能
     @Test
     public void testSort()throws Exception{
        //创建排序对象,Sort.Direction.ASC/DESC
         Sort sort= new Sort(Sort.Direction.ASC,"username");
         List list = employeeRepository.findAll(sort);
         list.forEach(e-> System.out.println(e));

     }
     //排序分页集成
    @Test
    public void testSortPage()throws Exception{
        //创建排序对象
        Sort sort = new Sort(Sort.Direction.ASC, "age");
        //创建分页对象,并将排序对象加入到分页中
        Pageable pageable=new PageRequest(0,10,sort);
        Page page = employeeRepository.findAll(pageable);
        page.forEach(e-> System.out.println(e));
    }

    //根据用户名进行查询
    @Test
    public void testFind01()throws Exception{
        Employee username = employeeRepository.findByUsername("admin");
        System.out.println(username);
    }
    //模糊查询
    @Test
    public void testFind02()throws Exception{
        List employeeList = employeeRepository.findByUsernameLike("%1%");
        employeeList.forEach(e-> System.out.println(e));
    }
    //多条件查询
    @Test
    public void test03()throws Exception{
        List byUsernameAndEmailLike = employeeRepository.findByUsernameLikeAndEmailLike("%1%", "%2%");
        byUsernameAndEmailLike.forEach(e-> System.out.println(e));
    }
    //根据用户名查询query
    @Test
    public void testQuery01()throws Exception{
        Employee query01 = employeeRepository.query01("admin12");
        System.out.println(query01);
    }
    //jpql 模糊查询
    @Test
    public void testQuery02()throws Exception{
        List query02 = employeeRepository.query02("%2%", "%2%");
        query02.forEach(e-> System.out.println(e));

    }
    //原生sql
    @Test
    public void testQuery03()throws Exception{
        Employee query03 = employeeRepository.query03("admin11");
        System.out.println(query03);

    }
    
    
    @Test
    public void testJpaSpecificationExecutor()throws Exception{
        List list = employeeRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //根据root拿到字段
                Path usernamepath = root.get("username");
                //对属性添加查询规则
                Predicate predicate = criteriaBuilder.like(usernamepath, "%1%");
                return predicate;
            }
        });
        list.forEach(e-> System.out.println(e));

    }
    //多条件查询
    @Test
    public void testJpaSpecificationExecutor02()throws Exception{
        List list = employeeRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path usernamePath = root.get("username");
                Predicate p1 = criteriaBuilder.like(usernamePath, "%2%");
                /*Path emailPath = root.get("email");
                Predicate p2 = criteriaBuilder.like(emailPath, "%2%");*/

                Path agePath = root.get("age");
                Predicate p3 = criteriaBuilder.gt(agePath, 25);
                Predicate predicate = criteriaBuilder.and(p1,p3);
                return predicate;
            }
        });
        list.forEach(e-> System.out.println(e));
    }
    /**
     * 多个条件查询+分页+排序
     * @throws Exception
     */
    @Test
    public void testJpaSpecificationExecutor03()throws Exception{
        //获取排序对象
        Sort sort=new Sort(Sort.Direction.DESC,"id");
        Pageable pageable =new PageRequest(0,4,sort);

        Page page = employeeRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path usernamePath = root.get("username");
                Predicate predicate = criteriaBuilder.like(usernamePath, "%1%");

                return predicate;
            }
        }, pageable);
        page.forEach(e-> System.out.println(e));
    }
    
    /*
    * 查询spec
    * */
    @Test
    public void testJpaSpec01()throws Exception{

        //获取到查询的规则
        Specification spec  = Specifications.and()
                .like("username", "%1%")
                .like("email","%2%")
                .build();
        //根据规则完成查询
        List list = employeeRepository.findAll(spec);

        list.forEach(e-> System.out.println(e));
    }
    //排序+分页+条件查询
    @Test
    public void testJpaSpec02()throws Exception{
        Sort sort=new Sort(Sort.Direction.DESC,"id");
        Pageable pageable=new PageRequest(0,2,sort);
        Specification spec=Specifications.and()
                .like("username","%1%")
                .build();
        Page page = employeeRepository.findAll(spec, pageable);
        page.forEach(e-> System.out.println(e));
    }

    //模拟前台用户传参
    @Test
    public void testJpaSpecQuery()throws Exception{
        EmployeeQuery query = new EmployeeQuery();
        query.setUsername("2");
        query.setEmail("2");
        query.setAge(22);
        //从query对象中获取到这个对象
        Specification spec = query.createSpec();
        List list = employeeRepository.findAll(spec);
        list.forEach(e-> System.out.println(e));
    }
    /*
    * 分页功能
    * */
    @Test
    public void testJpaSpecPageQuery()throws Exception{
        //模拟前台传参
        EmployeeQuery query = new EmployeeQuery();
        query.setUsername("1");
        //排序字段
        query.setOrderName("id");
        //排序类型
        query.setOrderType("DESC");
        //当前页
        query.setCurrentPage(2);
        //得到条件对象
        Specification spec = query.createSpec();
        //得到排序对象
         Sort sort = query.CreateSort();
         //得到分页对象
        Pageable pageable=new PageRequest(query.getJpaCurrentPage(),query.getPageSize(),sort);
        Page page = employeeRepository.findAll(spec, pageable);
        page.forEach(e-> System.out.println(e));

    }
    
}

 

 

 

 

 

你可能感兴趣的:(Spring+SpringDataJpa集成)