在相当长的一段时间里,实现应用程序的数据访问层非常麻烦。必须编写太多的模板代码来执行简单的查询,以及执行分页。Spring JPA旨在通过减少实际需要的工作量来显著改进数据访问层的实现。作为开发人员,您可以编写存储库接口,包括自定义查找程序方法。下面介绍 springboot集成JPA的使用:
JPA核心接口是Repository,其它所有接口都在此类的基础上进行了扩展。 下面是JPA关系图解图:
熟悉JPA的几个API
CurdRepository提供了增删改产方法,PagingAndSortingRepositroy增加了分页查询方法,JpaRepositroy又增加了实例查询方法。实际应用中可以有选择的继承上面接口即可。上面说过,jpa提供了封装查询数据库模板方法。下面就来一一介绍JPA给我们提供的模板方法:
CurdRepository
接口,提供增删改查基本的功能
@NoRepositoryBean
public interface CrudRepository extends Repository {
S save(S entity);
Iterable save(Iterable entities);
T findOne(ID id);
boolean exists(ID id);
Iterable findAll();
Iterable findAll(Iterable ids);
long count();
void delete(ID id);
void delete(T entity);
void delete(Iterable extends T> entities);
void deleteAll();
}
PagingAndSortingRepositroy
接口 ,分页查询,和排序
@NoRepositoryBean
public interface PagingAndSortingRepository extends CrudRepository {
//分类查询
Iterable findAll(Sort sort);
//分页查询
Page findAll(Pageable pageable);
}
JpaRepositroy
接口,提供实例查询方法
@NoRepositoryBean
public interface JpaRepository
extends PagingAndSortingRepository, QueryByExampleExecutor {
List findAll();
List findAll(Sort sort);
List findAll(Iterable ids);
List save(Iterable entities);
void flush();
S saveAndFlush(S entity);
void deleteInBatch(Iterable entities);
void deleteAllInBatch();
T getOne(ID id);
//实例查询
@Override
List findAll(Example example);
//实例查询,分类排序
@Override
List findAll(Example example, Sort sort);
}
SimpleRepository
实现类,增加了事务注解,进行事务管理,这就不介绍了,讲到自定义封装基类的时候会用到,一般都不会继承使用这个类.
二、使用
自定义一个PersonRepository接口继承上述任何一个接口都可以。不需要在接口上加@Repos