public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
<S extends T> S save(S entity); //保存实体
T findOne(ID primaryKey); //根据id查询实体
Iterable<T> findAll(); //查询所有实体
Long count(); //查询实体数量
void delete(T entity); //删除这个实体
boolean exists(ID primaryKey); //看这个id是否存在
}
CrudRepository 主要用于对实体的增删改查操作
PagingAndSortingRepository 继承CrudRepository 提供两个方法
public interface PagingAndSortingRepository<T, ID extends Serializable>
extends CrudRepository<T, ID> {
Iterable<T> findAll(Sort sort); //排序查询所有实体
Page<T> findAll(Pageable pageable); //分页查询所有实体
}
排序查询的时候定义一个sort 例如:
Sort sort = new Sort(Direction.DESC, "id") //这是一个对id进行反向排序,正向排序Direction.ASC
分页查询的时候定义一个pageable 例如:
Pageable pageable = new PageRequest(0, 10); //分页从第0页开始,每页显示10条记录
spring data jpa 根据方法规则的制定,产生不同的操作方式,自定义查询方法如:
public interface UserRepository extends CrudRepository<User, Long> {
Long countByLastname(String lastname); //根据lastname查询数据量
Long deleteByLastname(String lastname); //删除用户中 lastname 等于 #lastname 的数据
List<User> removeByLastname(String lastname); //删除用户中 lastname 等于 #lastname 的数据,返回数据集合
}
使用spring data定义一个持久化存储接口可以这样:
1.定义一个接口实现Repository ,并且Repository 的操作类型定义为你需要操作的实体类型和实体中ID的类型,例如:
interface PersonRepository extends Repository<Person, Long> { … }
2.在接口中定义一个查询方法
interface PersonRepository extends Repository<Person, Long> {
List<Person> findByLastname(String lastname); //根据lastname查询Person 数据集
}
3.通过java配置,让spring 创建一个代理实现类
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories
class Config {}
或者是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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<jpa:repositories base-package="com.acme.repositories"/>
</beans>
jpa:repositories 或者@EnableJpaRepositories 是一个特定的标签或者是注解,用于标识spring data jpa的操作
特别注意 当你使用注解的时候,是不需要配置base-package的,java 配置类是根据所在包的层级来寻找jpa配置管理的
4.获取定义接口并使用它,如:
public class SomeClient {
@Autowired
private PersonRepository repository;
public void doSomething() {
List<Person> persons = repository.findByLastname("Matthews");
}
}