JPA基礎及查詢規則 JPA JPA是Java Persistence API的簡稱,中文名Java持久層API,是JDK 5.0註解或XML描述對象-關係表的映射關係,並將運行期的實體對象持久化到資料庫中。 JPA框架中支持大數據集、事務、併發等容器級事務,這使得 JPA 超越了簡單持久化框架的局 ...
JPA基礎及查詢規則
JPA
JPA是Java Persistence API的簡稱,中文名Java持久層API,是JDK 5.0註解或XML描述對象-關係表的映射關係,並將運行期的實體對象持久化到資料庫中。
JPA框架中支持大數據集、事務、併發等容器級事務,這使得 JPA 超越了簡單持久化框架的局限,在企業應用發揮更大的作用。
Spring Boot使用JPA
首先在idea中創建項目的時候你就需要選擇JPA這一項,就會自動的在pom.xml文件中引入JPA的jar包
創建一個BaseDAO來繼承JpaRepository,這是根本也是基礎的,這裡的BaseDAO跟hibernate中的很相似,可以參照一下,DAO是一個項目的根本所在,寫好了他其他也差不多了
基本查詢
JPA基本查詢也分為兩種,一種是spring data預設已經實現,一種是根據查詢的方法來自動解析成SQL。
預設的直接在你的Controller中直接調用:
以下是看到大牛寫的,真是太好了,我只是搬運工
地址http://www.cnblogs.com/ityouknow/p/5891443.html
基本查詢
基本查詢也分為兩種,一種是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(Collectionage) | … 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;