Springboot 数据访问之JPA深刻

前言

上篇文章说起了JPA的相关简单使用,在这篇文章呢将深刻探讨JPA。在配置Repository服务类时扩展了CrudRepository这个接口,而正是许许多多的接口使咱们在使用JPA进行数据访问时会更加轻松app

Repository接口

Repository是个空接口,须要开发者在本身定义的接口中声明须要的方法。若定义的接口继承于Repository,则该接口会被IOC容器识别为一个Bean并归入IOC容器,进而能够在该接口中定一些符合命名规范的方法。也可用@RepositoryDefinition代替@Repository。定义的方法以find | get | read开头;涉及有条件查询时条件的属性(大写字母开头)用条件关键字链接;@Query能够自定义JPQL语句进行查询。code


CrudRepository接口

不一样于Repository,它是个能提供许多实现方法的接口。
T.save(T entity) 保存单个实体
iterable<T>save(iterable <?extends T>entities);保存集合
T findOne(ID id)根据ID查找实体
boolean exists(ID id)判断实体是否存在
iterable<T>findAll()查询全部实体
long count() 查询实体数量
void delete(ID id) 根据ID删除实体
void delete(T entity)删除一个实体
void delete(ilterable<?extends T>entities);删除一个实体的集合
void deleteAll()删除全部实体排序


PagingAndSortingRepository接口

ilterable<T>findAll(Sort sort)排序功能
Page<T>findAll(Pageable pageable)分页查询并排序继承


用find+大写字母编写查询方法

  • dao层
public interface person2Repository extends JpaRepository<Person,Integer> {
    public Person findByName(String name);}
  • services层
@Resource
    private person2Repository person2Repository;
    @Transactional
    public Person findByName(String name){
        return person2Repository.findByName(name);
    }
  • Controller
@RequestMapping("/findByPersonName")
    public Person findByName(String name){
        return personService.findByName(name);
    }

使用注解@Query 自定义JPQL语句进行查询

  • Dao层
public interface person2Repository extends JpaRepository<Person,Integer> {
            @Query("select P from Person P where P.name = :pname")
            public Person findMyName(@Param("pname")String name);
}
  • 服务层
@Resource
    private person2Repository person2Repository;
   @Transactional
    public Person findMyName(String name){
        return person2Repository.findMyName(name);
   }
  • 控制器
@RequestMapping("/findMyName")
       public Person findMyName(String name){
        return personService.findMyName(name);}
相关文章
相关标签/搜索