一、SpringData入門
在上次學SpringBoot的時候,那時候的教程就已經涉及到了一點SpringData JPA的知識了。當時還是第一次見,覺得也沒什么大不了,就是封裝了Hibernate的API而已。
然后在慕課網上又看到了SpringData的教程了。於是就進去學習了一番。
教程地址:https://www.imooc.com/learn/821
源碼下載地址:https://img.mukewang.com/down/58e60b910001594b00000000.zip
在教程中是以原始JDBC和Spring JDBC Template來進行引入SpringData的。
由於原始的JDBC和Spring JDBC Template需要書寫的代碼量還是比較多的,於是我們就有了SpringData這么一個框架了。
1.1SpringDataJPA入門
SpringData JPA只是SpringData中的一個子模塊
JPA是一套標准接口,而Hibernate是JPA的實現
SpringData JPA 底層默認實現是使用Hibernate
SpringDataJPA 的首個接口就是Repository,它是一個標記接口。只要我們的接口實現這個接口,那么我們就相當於在使用SpringDataJPA了。
只要我們實現了這個接口,我們就可以使用"按照方法命名規則"來進行查詢。我第一次見到他的時候覺得他賊神奇。
1.2項目配置
- 在pom.xml中添加相關依賴
- 在yml或者properties文件種配置對應的屬性
- 創建實體和Repository測試
參考資源:
- http://blog.csdn.net/pdw2009/article/details/51115044
- http://blog.csdn.net/w_x_z_/article/details/53174308
例子:
比如:定義下面這么一個方法,就可以在外界使用了。
Employee findByName(String name);
也就是說,上面的方法會被解析成SQL語句:select * from Employee where name = ?
是不是覺得很方便!!!!
如果是簡單的操作的話,直接定義這么一個方法,就能夠使用了。確確實實很好。
簡直比Mytais不知道好到哪里去了。Mybatis還要去寫映射文件,專門寫一個sql語句。
同時,創建了實體就能夠自動幫我們創建數據庫表了,修改了實體字段也能夠將數據表一起修改。頓時就覺得很好用了。
/**
* 雇員: 先開發實體類===>自動生成數據表
*/
@Entity
public class Employee {
private Integer id;
private String name;
private Integer age;
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length = 20)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
當然了,上面根據方法名來使用是有弊端的:
- 1)方法名會比較長: 約定大於配置
- 2)對於一些復雜的查詢,是很難實現
比如:
// where name like ?% and age <?
public List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);
// where name like %? and age <?
public List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);
// where name in (?,?....) or age <?
public List<Employee> findByNameInOrAgeLessThan(List<String> names, Integer age);
// where name in (?,?....) and age <?
public List<Employee> findByNameInAndAgeLessThan(List<String> names, Integer age);
因此,對於這種情況下還是要寫SQL語句簡單得多。
@Query("select o from Employee o where id=(select max(id) from Employee t1)")
public Employee getEmployeeByMaxId();
@Query("select o from Employee o where o.name=?1 and o.age=?2")
public List<Employee> queryParams1(String name, Integer age);
@Query("select o from Employee o where o.name=:name and o.age=:age")
public List<Employee> queryParams2(@Param("name")String name, @Param("age")Integer age);
@Query("select o from Employee o where o.name like %?1%")
public List<Employee> queryLike1(String name);
@Query("select o from Employee o where o.name like %:name%")
public List<Employee> queryLike2(@Param("name")String name);
@Query(nativeQuery = true, value = "select count(1) from employee")
public long getCount();
學過Hibernate的都知道上面的不是原生的SQL語句,是HQL/JPQL語句。不過他用起來還是比Mybatis簡潔很多。
對於修改數據,需要增加Modify注解、並且一定要在事務的管理下才能修改數據
@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
public void update(@Param("id")Integer id, @Param("age")Integer age);
1.3Repository子類接口
CURDRepository接口的實現方法:
排序、分頁接口:
增加過濾條件的接口:
JPA接口:
JpaRepository繼承PagingAndSortingRepository,PagingAndSortingRepository又繼承CrudRepository,也就是說我們平時自定義的接口只要繼承JpaRepository,就相當於擁有了增刪查改,分頁,等等功能。
二、JPQL基礎#
原來JPQL是JPA的一種查詢語言,之前我是認為它和HQL是一樣的。其實是兩個概念。不過它們用起來還真是差不多。
無非就是:JPA對應JPQL,而Hibernate對應HQL而已。都是面向對象的查詢語言。
2.1 Criteria查詢##
這里就涵蓋了很多的條件了。
2.2 Specification接口使用
其實這個接口的API就和Criteria是一樣的,看懂了Criteria API,這個接口就會用了。
2.3 nameQuery注解##
2.4query注解##
2.5 小總結
https://www.zhihu.com/question/53706909
引入知乎的一段回答:
基本的增刪改查和調用存儲過程通過Spring Data JPA Repository來解決
稍微復雜的查詢或是批量操作使用QueryDSL或Spring Data Specification的API來解決
特別特別復雜的查詢操作可以使用Spring Data JPA Repository的注解定義native sql來解決
三、需要注意的地方
3.1 注解寫在get方法上
剛開始用的時候我以為注解是寫在屬性上,但是遇到了很多的bug,在網上的解決方案又是很少。
遇到了一個Bug,在國內的論壇幾乎都找不到答案:
org.hibernate.property.access.spi.PropertyAccessBuildingException: Could not locate field nor getter method for property named [cn.itheima.web.domain.Customer#cust_user_id]
搞得頭都大了都沒有找到合適的方法,不知道是哪里錯了。
后來去看了JPA的一對多、多對一的博文去參考了一下,感覺我還是沒有錯。
最后才發現大多數的博文都是在get方法上寫注解的,而我就在屬性上直接寫注解了。
在Get方法上寫注解的原因是不用破壞我們的封裝性,我直接在屬性上寫注解,而屬性是private來進行修飾的。這也導致了我出現這個錯誤的原因。
3.2級聯 .ALL慎用
在保存數據的時候,我以為直接使用casecade.ALL是最方便的,但是還出現了Bug。后來找到了答案:http://blog.csdn.net/csujiangyu/article/details/48223641
3.3@OneToOne的注解
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public@interfaceOneToOne {
Class targetEntity() default void.class;
CascadeType[]cascade()default();
FetchType fetch() default EAGER;
boolean optional() default true;
String mappedBy() default "";
}
1,targetEntity 屬性表示默認關聯的實體類型,默認為當前標注的實體類。
2,cascade屬性表示與此實體一對一關聯的實體的級聯樣式類型。
3,fetch屬性是該實體的加載方式,默認為即時加載EAGER
4,optional屬性表示關聯的該實體是否能夠存在null值,默認為ture,如果設置為false,則該實體不能為null,
5, mapperBy屬性:指關系被維護端
3.4@JoinColumn注解
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public@interfaceJoinColumn {
String name() default "";
String referencedColumnName() default "";
boolean unique() default false;
boolean nullable() default true;
boolean insertable() default true;
booleanupdatabledefaulttrue;
String columnDefinition() default "";
String table() default "";
}
1,@JoinColumn注釋是保存表與表之間關系的字段
2,如果不設置name,默認name = 關聯表的名稱+”-“+關聯表主鍵的字段名,在上面實例3,中,默認為“address_id” **
默認情況下,關聯實體的主鍵一般是用來做外鍵的,但如果此時不想用主鍵作為外鍵,則需要設置referencedColumnName屬性,如:**
create table address (
id int(20) not null auto_increament,
ref_id int(20) notn ull,
province varchar(50),
city varchar(50),
postcode varchar(50),
detail varchar(50),
primary key(id)
)
@OneToOne@JoinColumn(name="address_id", referencedColumnName="ref_id")
private AddressEO address;
四、擴展閱讀
后來我使用了SpringData JPA用於一個簡單的項目,從中也遇到了不少的問題和相關的沒有接觸到的知識點。下面我會給出當時搜索到的資料和遇到的問題以及解決方案
4.1遇到的問題以及解決資料
SpringData JPA遇到的問題有:
參考資料:
-
https://www.cnblogs.com/sevenlin/p/sevenlin_sprindatajpa20150725.html
-
CascadeType jpa spring 理解:最好在開始的使用只使用REFRESH,當遇到問題的時候再添加MERGER等等,不然一開始會很亂
-
一對多,多對一的配置問題。注解寫在GETTER方法上,不要寫在屬性上。這樣會避免很多不必要的錯誤
- https://www.jianshu.com/p/0a2163273b3e
- http://blog.csdn.net/ABAP_Brave/article/details/52845986
- http://blog.csdn.net/lyg_2012/article/details/70195062
- http://blog.sina.com.cn/s/blog_76c4136a0102y70d.html
- http://blog.csdn.net/mendeliangyang/article/details/52366799/
- https://www.jianshu.com/p/5c416a780b3e
-
異常處理:
- detached entity passed to persist異常:
- JPA一堆多循環引用錯誤 HttpMessageNotWritableException:
五、總結
總的來說,如果是單表操作的話,那么SpringData JPA是十分方便的,如果是比較復雜的業務的話,那么使用SpringData JPA就有點麻煩了,因為它返回的是Object[]
,返回的結果還要手動進行封裝,不太方便。靈活性很低...
各類知識點總結
下面的文章都有對應的原創精美PDF,在持續更新中,可以來找我催更~
- 92頁的Mybatis
- 129頁的多線程
- 141頁的Servlet
- 158頁的JSP
- 76頁的集合
- 64頁的JDBC
- 105頁的數據結構和算法
- Spring家族
- Hibernate
- AJAX
- 監聽器和過濾器
- ......
涵蓋Java后端所有知識點的開源項目(已有7 K star):https://github.com/ZhongFuCheng3y/3y
如果大家想要實時關注我更新的文章以及分享的干貨的話,微信搜索Java3y。
PDF文檔的內容均為手打,有任何的不懂都可以直接來問我(公眾號有我的聯系方式)。