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);}
相關文章
相關標籤/搜索