天天看點

springboot:spring data jpa介紹

轉載自:https://www.cnblogs.com/ityouknow/p/5891443.html

在上篇文章springboot(二):web綜合開發中簡單介紹了一下spring data jpa的基礎性使用,這篇文章将更加全面的介紹spring data jpa 常見用法以及注意事項

使用spring data jpa 開發時,發現國内對spring boot jpa全面介紹的文章比較少案例也比較零碎,是以寫文章總結一下。本人也正在翻譯Spring Data JPA 參考指南,有興趣的同學歡迎聯系我,一起加入翻譯中!

spring data jpa介紹

首先了解JPA是什麼?

JPA(Java Persistence API)是Sun官方提出的Java持久化規範。它為Java開發人員提供了一種對象/關聯映射工具來管理Java應用中的關系資料。他的出現主要是為了簡化現有的持久化開發工作和整合ORM技術,結束現在Hibernate,TopLink,JDO等ORM架構各自為營的局面。值得注意的是,JPA是在充分吸收了現有Hibernate,TopLink,JDO等ORM架構的基礎上發展而來的,具有易于使用,伸縮性強等優點。從目前的開發社群的反應上看,JPA受到了極大的支援和贊揚,其中就包括了Spring與EJB3.0的開發團隊。

注意:JPA是一套規範,不是一套産品,那麼像Hibernate,TopLink,JDO他們是一套産品,如果說這些産品實作了這個JPA規範,那麼我們就可以叫他們為JPA的實作産品。

spring data jpa

Spring Data JPA 是 Spring 基于 ORM 架構、JPA 規範的基礎上封裝的一套JPA應用架構,可使開發者用極簡的代碼即可實作對資料的通路和操作。它提供了包括增删改查等在内的常用功能,且易于擴充!學習并使用 Spring Data JPA 可以極大提高開發效率!

spring data jpa讓我們解脫了DAO層的操作,基本上所有CRUD都可以依賴于它來實作

基本查詢

基本查詢也分為兩種,一種是spring data預設已經實作,一種是根據查詢的方法來自動解析成SQL。

預先生成方法

spring data jpa 預設預先生成了一些基本的CURD的方法,例如:增、删、改等等

1 繼承JpaRepository

public interface UserRepository extends JpaRepository<User, Long> {
}           

2 使用預設方法

@Test
public void testBaseQuery() throws Exception {
    User user=new User();
    userRepository.findAll();
    userRepository.findOne(1l);
    userRepository.save(user);
    userRepository.delete(user);
    userRepository.count();
    userRepository.exists(1l);
    // ...
}           

就不解釋了根據方法名就看出意思來

自定義簡單查詢

自定義的簡單查詢就是根據方法名來自動生成SQL,主要的文法是

findXXBy

,

readAXXBy

,

queryXXBy

,

countXXBy

getXXBy

後面跟屬性名稱:

User findByUserName(String userName);           

也使用一些加一些關鍵字

And

、 

Or

User findByUserNameOrEmail(String username, String email);           

修改、删除、統計也是類似文法

Long deleteById(Long id);

Long countByUserName(String userName)           

基本上SQL體系中的關鍵詞都可以使用,例如:

LIKE

、 

IgnoreCase

、 

OrderBy

List<User> findByEmailLike(String email);

User findByUserNameIgnoreCase(String userName);
    
List<User> findByUserNameOrderByEmailDesc(String email);           

具體的關鍵字,使用方法和生産成SQL如下表所示

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

複雜查詢

在實際的開發中我們需要用到分頁、删選、連表等查詢的時候就需要特殊的方法或者自定義SQL

分頁查詢

分頁查詢在實際使用中非常普遍了,spring data jpa已經幫我們實作了分頁的功能,在查詢的方法中,需要傳入參數

Pageable

,當查詢中有多個參數的時候

Pageable

建議做為最後一個參數傳入

Page<User> findALL(Pageable pageable);
    
Page<User> findByUserName(String userName,Pageable pageable);           

Pageable

 是spring封裝的分頁實作類,使用的時候需要傳入頁數、每頁條數和排序規則

@Test
public void testPageQuery() throws Exception {
    int page=1,size=10;
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    userRepository.findALL(pageable);
    userRepository.findByUserName("testName", pageable);
}           

限制查詢

有時候我們隻需要查詢前N個元素,或者支取前一個實體。

ser findFirstByOrderByLastnameAsc();

User findTopByOrderByAgeDesc();

Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);

List<User> findFirst10ByLastname(String lastname, Sort sort);

List<User> findTop10ByLastname(String lastname, Pageable pageable);           

自定義SQL查詢

其實Spring data 覺大部分的SQL都可以根據方法名定義的方式來實作,但是由于某些原因我們想使用自定義的SQL來查詢,spring data也是完美支援的;在SQL的查詢方法上面使用

@Query

注解,如涉及到删除和修改在需要加上

@Modifying

.也可以根據需要添加 

@Transactional

 對事物的支援,查詢逾時的設定等

@Modifying
@Query("update User u set u.userName = ?1 where c.id = ?2")
int modifyByIdAndUserId(String  userName, Long id);
    
@Transactional
@Modifying
@Query("delete from User where id = ?1")
void deleteByUserId(Long id);
  
@Transactional(timeout = 10)
@Query("select u from User u where u.emailAddress = ?1")
    User findByEmailAddress(String emailAddress);           

多表查詢

多表查詢在spring data jpa中有兩種實作方式,第一種是利用hibernate的級聯查詢來實作,第二種是建立一個結果集的接口來接收連表查詢後的結果,這裡主要第二種方式。

首先需要定義一個結果集的接口類。

public interface HotelSummary {

    City getCity();

    String getName();

    Double getAverageRating();

    default Integer getAverageRatingRounded() {
        return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
    }

}           

查詢的方法傳回類型設定為新建立的接口

@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
        - "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
Page<HotelSummary> findByCity(City city, Pageable pageable);

@Query("select h.name as name, avg(r.rating) as averageRating "
        - "from Hotel h left outer join h.reviews r  group by h")
Page<HotelSummary> findByCity(Pageable pageable);           

使用

Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));
for(HotelSummary summay:hotels){
        System.out.println("Name" +summay.getName());
    }           
在運作中Spring會給接口(HotelSummary)自動生産一個代理類來接收傳回的結果,代碼彙總使用

getXX

的形式來擷取

多資料源的支援

同源資料庫的多源支援

日常項目中因為使用的分布式開發模式,不同的服務有不同的資料源,常常需要在一個項目中使用多個資料源,是以需要配置sping data jpa對多資料源的使用,一般分一下為三步:

  • 1 配置多資料源
  • 2 不同源的實體類放入不同包路徑
  • 3 聲明不同的包路徑下使用不同的資料源、事務支援

這裡有一篇文章寫的很清楚:Spring Boot多資料源配置與使用

異構資料庫多源支援

比如我們的項目中,即需要對mysql的支援,也需要對mongodb的查詢等。

實體類聲明

@Entity

 關系型資料庫支援類型、聲明

@Document

 為mongodb支援類型,不同的資料源使用不同的實體就可以了

interface PersonRepository extends Repository<Person, Long> {
 …
}

@Entity
public class Person {
  …
}

interface UserRepository extends Repository<User, Long> {
 …
}

@Document
public class User {
  …
}           

但是,如果User使用者既使用mysql也使用mongodb呢,也可以做混合使用

interface JpaPersonRepository extends Repository<Person, Long> {
 …
}

interface MongoDBPersonRepository extends Repository<Person, Long> {
 …
}

@Entity
@Document
public class Person {
  …
}           

也可以通過對不同的包路徑進行聲明,比如A包路徑下使用mysql,B包路徑下使用mongoDB

@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")
@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")
interface Configuration { }           

其它

使用枚舉

使用枚舉的時候,我們希望資料庫中存儲的是枚舉對應的String類型,而不是枚舉的索引值,需要在屬性上面添加

@Enumerated(EnumType.STRING)

 注解

@Enumerated(EnumType.STRING) 
@Column(nullable = true)
private UserType type;           

不需要和資料庫映射的屬性

正常情況下我們在實體類上加入注解

@Entity

,就會讓實體類和表相關連如果其中某個屬性我們不需要和資料庫來關聯隻是在展示的時候做計算,隻需要加上

@Transient

屬性既可。

@Transient
private String  userName;           

源碼案例

這裡有一個開源項目幾乎使用了這裡介紹的所有标簽和布局,大家可以參考:

cloudfavorites

參考

Spring Data JPA - Reference Documentation

Spring Data JPA——參考文檔 中文版

作者:純潔的微笑

出處:http://www.ityouknow.com/

版權所有,歡迎保留原文連結進行轉載:)