Spring Data——Repository的子接口

1.CrudRepository 接口:

CrudRepository 接口提供了最基本的对实体类的添删改查操作 

T save(T entity);//保存单个实体 

Iterable<T> save(Iterable<? extends T> entities);//保存集合       

T findOne(ID id);//根据id查找实体        

boolean exists(ID id);//根据id判断实体是否存在        

Iterable<T> findAll();//查询所有实体,不用或慎用!        

long count();//查询实体数量        

void delete(ID id);//根据Id删除实体        

void delete(T entity);//删除一个实体 

void delete(Iterable<? extends T> entities);//删除一个实体的集合        

void deleteAll();//删除所有实体,不用或慎用! 

@Test
	public void testCrudReposiory(){
		List<Person> persons = new ArrayList<>();
		
		for(int i = 'a'; i <= 'z'; i++){
			Person person = new Person();
			person.setAddressId(i + 1);
			person.setBirth(new Date());
			person.setEmail((char)i + "" + (char)i + "@atguigu.com");
			person.setLastName((char)i + "" + (char)i);
			
			persons.add(person);
		}
		
		personService.savePersons(persons);
	}

2.PagingAndSortingRepository接口:

该接口提供了分页与排序功能

Iterable<T> findAll(Sort sort); //排序

Page<T> findAll(Pageable pageable); //分页查询(含排序功能)

@Test
	public void testPagingAndSortingRespository(){
		int pageNo = 6 - 1;
		int pageSize = 5;
		Order order1 = new Order(Direction.DESC, "id");
		Order order2 = new Order(Direction.ASC, "email");
		Sort sort = new Sort(order1, order2);
		
		PageRequest pageable = new PageRequest(pageNo, pageSize, sort);
		Page<Person> page = personRepsotory.findAll(pageable);
		
		System.out.println(page.getTotalElements());
		System.out.println(page.getNumber());
		System.out.println(page.getTotalPages());
		System.out.println(page.getContent());
		System.out.println(page.getNumberOfElements());
	}

3.JpaRepository接口:

该接口提供了JPA的相关功能

List<T> findAll(); //查找所有实体

List<T> findAll(Sort sort); //排序、查找所有实体

List<T> save(Iterable<? extends T> entities);//保存集合

void flush();//执行缓存与数据库同步

T saveAndFlush(T entity);//强制执行持久化

void deleteInBatch(Iterable<T> entities);//删除一个实体集合

@Test
	public void testJpaRepository(){
		Person person = new Person();
		person.setBirth(new Date());
		person.setEmail("[email protected]");
		person.setLastName("xyz");
		person.setId(28);
		
        //类似于merge
		Person person2 = personRepsotory.saveAndFlush(person);
		
		System.out.println(person == person2);
	}

4.JpaSpecificationExecutor接口:

不属于Repository体系,实现一组 JPA Criteria 查询相关的方法 

Specification:封装  JPA Criteria 查询条件。通常使用匿名内部类的方式来创建该接口的对象

public interface PersonRepsotory extends 
	JpaRepository<Person, Integer>,
	JpaSpecificationExecutor<Person>{
...
}
/**
* 实现带查询条件的的分页,id>5为条件
* 调用JpaSpecificationExecutor的Page<T> findAll(Specification<T> spec, Pageable pageable);
* Specification 封装了JPA Criteria查询的查询条件
* Pageable 封装了请求分页的信息:pageNo,pageSize,Sort
*/
@Test
	public void testJpaSpecificationExecutor(){
		int pageNo = 3 - 1;
		int pageSize = 5;
		PageRequest pageable = new PageRequest(pageNo, pageSize);
		
        //通常使用Specification的匿名内部类
		Specification<Person> specification = new Specification<Person>() {
            /**
            * root 代表查询的实体
            * query 可以从中得到Root对象,即告诉Criteria查询要查询哪个实体类,还可以来添加查询条件,还可以结合EntityManager对象得到最终查询的TypeQuery对象
            * cb 用于创建Criteria相关对象的工厂,可以从中获取到Predicate对象
            */
			@Override
			public Predicate toPredicate(Root<Person> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				Path path = root.get("id");
				Predicate predicate = cb.gt(path, 5);
				return predicate;
			}
		};
		
		Page<Person> page = personRepsotory.findAll(specification, pageable);
		
		System.out.println(page.getTotalElements());
		System.out.println((page.getNumber() + 1));
		System.out.println(page.getTotalPages());
		System.out.println(page.getContent());
}

5.自定义 Repository 方法:

5.1 为某一个 Repository 上添加自定义方法:

步骤:

定义一个接口: 声明要添加的, 并自实现的方法

提供该接口的实现类: 类名需在要声明的 Repository 后添加 Impl, 并实现方法

声明 Repository 接口, 并继承 1) 声明的接口

使用.

注意:默认情况下, Spring Data 会在 base-package 中查找 "接口名Impl" 作为实现类. 也可以通过 repository-impl-postfix 声明后缀.

package com.atguigu.springdata;

public interface PersonDao {
	
	void test();
	
}
package com.atguigu.springdata;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class PersonRepsotoryImpl implements PersonDao {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public void test() {
		Person person = entityManager.find(Person.class, 11);
		System.out.println("-->" + person);
	}

}
public interface PersonRepsotory extends 
	JpaRepository<Person, Integer>,
	JpaSpecificationExecutor<Person>, PersonDao{}
@Test
	public void testCustomRepositoryMethod(){
		personRepsotory.test();
	}

5.2 为所有的 Repository 都添加自实现的方法:

步骤:

声明一个接口, 在该接口中声明需要自定义的方法, 且该接口需要继承 Spring Data 的 Repository.

提供 1) 所声明的接口的实现类. 且继承 SimpleJpaRepository, 并提供方法的实现

定义 JpaRepositoryFactoryBean 的实现类, 使其生成 1) 定义的接口实现类的对象

修改 <jpa:repositories /> 节点的 factory-class 属性指向 3) 的全类名

注意: 全局的扩展实现类不要用 Imp 作为后缀名, 或为全局扩展接口添加 @NoRepositoryBean 注解告知  Spring Data:Spring Data 不把其作为 Repository

猜你喜欢

转载自blog.csdn.net/qq_38386085/article/details/85261133