閱讀807 返回首頁    go 阿裏雲 go 技術社區[雲棲]


springboot(五):spring data jpa的使用

在上篇文章 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 聲明不同的包路徑下使用不同的數據源、事務支持

異構數據庫多源支持

比如我們的項目中,即需要對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;

作者:純潔的微笑
原文鏈接

最後更新:2017-05-31 14:31:39

  上一篇:go  原生js調用json方法
  下一篇:go  《Spring 3.0就這麼簡單》——1.8 小結