慕课网_《轻松愉快之玩转SpringData》第五章学习总结4

本文详细介绍了SpringDataJPA的高级应用,包括CrudRepository、PagingAndSortingRepository、JpaRepository及EmployeeJpaSpecificationExecutorRepository接口的使用方法,涵盖实体保存、查询、排序、分页及批量操作等关键功能。

第五章:Spring Data JPA高级

5-1CrudRepository接口使用详解

CrudRepository接口使用详情

save(entity) :保存一个实体
save(entities):保存多个实体
findOne(id) :找到一个对象
exists(id):根据ID判断对象是否存在
findAll():找到所有实体对象
delete(id):根据ID删除实体对象
delete(entity):根据实体对象删除实体对象
delete(entities):删除多个实体对象
deleteAll():删除所有实体对象

代码详情:
1.在repository新建一个接口EmployeeCrudRepository继承CrudRepository借口

import com.imooc.domain.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface EmployeeCrudRepository extends CrudRepository <Employee , Integer> {

}

2.编写EmployeeCrudRepositoryTest单元测试类

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.imooc.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class EmployeeCrudRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeeCrudRepository employeeCrudRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeCrudRepository = cxt.getBean(EmployeeCrudRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void TestSave() {
        List<Employee> employees = new ArrayList<Employee>();
        Employee employee = null;
        for (int i = 0; i < 100; i++) {
            employee = new Employee();
            employee.setName("test" + i);
            employee.setAge(100 - i);
            employees.add(employee);

        }
        employeeCrudRepository.save(employees);
    }
}

5-2 PagingAndSortingRespository接口使用详情

1.该接口包含分页和排序的功能
2.带排序的查询:findAll(Sort sort) 可排序的对象Sort,把排序的字段传进去
3.带排序的分页查询:findAll(Pageable pageable) 可分页的对象Pageable

接口传什么参数,按ctrl+点击CrudRepository,查看源码,

public interface EmployeeCrudRepository extends CrudRepository <Employee , Integer>

源码
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

传入参数为<T, ID extends Serializable>,T为实体类,ID为主键的类型

1.新建接口EmployeePagingAndSortingRepository

package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository <Employee,Integer>{
}

2.接口测试EmployeePagingAndSortingRepositoryTest类

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.imooc.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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 java.util.ArrayList;
import java.util.List;

public class EmployeePagingAndSortingRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeePagingAndSortingRepository employeePagingAndSortingRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeePagingAndSortingRepository = cxt.getBean(EmployeePagingAndSortingRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void testPage(){
        //int page:index是从0开始,不是从1开始
        Pageable pageable = new PageRequest(1, 9);
        Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
        System.out.println("总页数"+page.getTotalPages());
        System.out.println("总记录数"+(page.getTotalElements()+1));
        System.out.println("当前第几页"+page.getNumber());
        System.out.println("当前页的集合"+page.getContent());
        System.out.println("当前页面的记录数"+page.getNumberOfElements());
    }
    @Test
    public void sortTest(){
        /**desc 倒叙,asc 升序*/
        Sort.Order order = new Sort.Order(Sort.Direction.ASC ,"id");
        Sort sort = new Sort(order);/**构建一个sort*/
        //int page:index是从0开始,不是从1开始
        Pageable pageable = new PageRequest(0, 5, sort);
        Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);

        System.out.println("总页数"+page.getTotalPages());
        System.out.println("总记录数"+(page.getTotalElements()+1));
        System.out.println("当前第几页"+page.getNumber());
        System.out.println("当前页的集合"+page.getContent());
        System.out.println("当前页面的记录数"+page.getNumberOfElements());

    }
}

5-3JpaRepository接口使用详情

JpaRepository接口简介
findAll:查询所有记录
findAll(Sort sort):查询所有记录并排序
save(entities):保存多个实体对象
flush:刷新缓存区
deleteInBatch(entities):一个批次内删除那些实体对象

1.新建一个借口EmployeeJpaRepository

package com.imooc.repository;

import com.imooc.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

public interface EmployeeJpaRepository extends JpaRepository <Employee , Integer> {

}

2.新建测试类 EmployeeJpaRepositoryTest

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.imooc.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class EmployeeJpaRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeeJpaRepository employeeJpaRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeJpaRepository = cxt.getBean(EmployeeJpaRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void TestFind() {
        Employee employee = employeeJpaRepository.findOne(5);

        System.out.println( employee);
        System.out.println(employeeJpaRepository.exists(5));
        System.out.println(employeeJpaRepository.exists(101));

    }

}

5-4 EmployeeJpaSpecificationExecutorRepository(比上面的接口多过虑条件)

Specification封装了JPA Criteria查询条件
criteria()
过虑条件:

 Specification<Employee> specification = new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                //root(employee(age))
                Path path = root.get("age");
                return  criteriaBuilder.gt(path,50);
            }
        };

1.创建接口EmployeeJpaSpecificationExecutorRepository

package com.imooc.repository;

import com.imooc.domain.Employee; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository;

public interface EmployeeJpaSpecificationExecutorRepository extends JpaRepository <Employee , Integer> , JpaSpecificationExecutor <Employee>{

}
2.测试类EmployeeJpaSpecificationExecutorRepositoryTest
package com.imooc.repository;

import com.imooc.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
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 javax.persistence.criteria.*;
import javax.swing.text.html.HTMLDocument;
import java.util.List;

public class EmployeeJpaSpecificationExecutorRepositoryTest {
private ApplicationContext cxt =null ;
private EmployeeJpaSpecificationExecutorRepository employeeJpaSpecificationExecutorRepository = null ;

@Before
public void setup(){
    cxt = new ClassPathXmlApplicationContext("beansnew.xml");
    employeeJpaSpecificationExecutorRepository = cxt.getBean(EmployeeJpaSpecificationExecutorRepository.class);
    System.out.println("setup");
}
@After
public void tearDown(){
    cxt = null ;
    System.out.println("tearDown");
}

/**
 * 1.排序传给Sort.Order order ,
 * 2,分页Pageable pageable = new PageRequest(0, 5, sort);,
 * 3.查询条件:age >50
 */
@Test
public void TestQuery() {
    /**desc 倒叙,asc 升序*/
    Sort.Order order = new Sort.Order(Sort.Direction.DESC,"id");
    Sort sort = new Sort(order);/**构建一个sort*/
    //int page:index是从0开始,不是从1开始
    Pageable pageable = new PageRequest(0, 5, sort);
    /**
     * root :就是我们要查询的类型(employee)
     * query:添加查询条件
     * cb:构建Predicate(断言)
     */
    Specification<Employee> specification = new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root,
                                     CriteriaQuery<?> criteriaQuery,
                                     CriteriaBuilder criteriaBuilder) {
            //root(employee(age))
            Path path = root.get("age");
            return  criteriaBuilder.gt(path,50);
        }
    };
    Page<Employee> page = employeeJpaSpecificationExecutorRepository.findAll(specification,pageable);

// Page page = employeeJpaSpecificationExecutorRepository.findAll(pageable);

    System.out.println("总页数"+page.getTotalPages());
    System.out.println("总记录数"+page.getTotalElements());
    System.out.println("当前第几页"+page.getNumber()+1);
    System.out.println("当前页的集合"+page.getContent());
    System.out.println("当前页面的记录数"+page.getNumberOfElements());

    Employee employee = employeeJpaSpecificationExecutorRepository.findOne(5);
    System.out.println(employee);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值