更多請關注公衆號html
JPA
(Java Persistence API
)意即Java持久化API,是Sun官方在JDK5.0後提出的Java持久化規範(JSR 338,這些接口所在包爲javax.persistence
,詳細內容可參考https://github.com/javaee/jpa-spec)
JPA的出現主要是爲了簡化持久層開發以及整合ORM技術,結束Hibernate、TopLink、JDO等ORM框架各自爲營的局面。JPA是在吸取現有ORM框架的基礎上發展而來,易於使用,伸縮性強。總的來講,JPA包括如下3方面的技術:java
JPQL
)查詢數據,避免程序的SQL語句緊密耦合來看一下Spring官方的解釋https://spring.io/projects/spring-data-jpa#overviewmysql
Spring Data JPA是Spring Data家族的一部分,能夠輕鬆實現基於JPA的存儲庫。 此模塊處理對基於JPA的數據訪問層的加強支持。 它使構建使用數據訪問技術的Spring驅動應用程序變得更加容易。git
在至關長的一段時間內,實現應用程序的數據訪問層一直很麻煩。 必須編寫太多樣板代碼來執行簡單查詢以及執行分頁和審計。 Spring Data JPA旨在經過減小實際須要的工做量來顯著改善數據訪問層的實現。 做爲開發人員,您編寫repository接口,包括自定義查找器方法,Spring將自動提供實現。github
這個問題可參考https://stackoverflow.com/questions/16148188/spring-data-jpa-versus-jpa-whats-the-difference及https://blog.csdn.net/u014421556/article/details/52635000web
總的來講JPA是ORM規範,Hibernate、TopLink等是JPA規範的具體實現,這樣的好處是開發者能夠面向JPA規範進行持久層的開發,而底層的實現則是能夠切換的。Spring Data Jpa則是在JPA之上添加另外一層抽象(Repository層的實現),極大地簡化持久層開發及ORM框架切換的成本。spring
在Spring Boot沒出來以前若是要採用Java Configuration來配置Spring Data Jpa你須要配置以下的Bean
參考自Spring In Action及Spring Data Jpa官方文檔5.1.2. Annotation-based Configurationsql
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; /** * 注意:spring-data-jpa2.x版本須要spring版本爲5.x * 不然會報Initialization of bean failed; nested exception is java.lang.AbstractMethodError錯誤 * 參考:https://stackoverflow.com/questions/47558017/error-starting-a-spring-application-initialization-of-bean-failed-nested-excep * 搭配方案:spring4+spring-data-jpa1.x或spring5+spring-data-jpa2.x */ @Configuration // 藉助spring data實現自動化的jpa repository,只需編寫接口無需編寫實現類 // 至關於xml配置的<jpa:repositories base-package="com.example.repository" /> // repositoryImplementationPostfix默認就是Impl // entityManagerFactoryRef默認就是entityManagerFactory // transactionManagerRef默認就是transactionManager @EnableJpaRepositories(basePackages = {"com.example.repository"}, repositoryImplementationPostfix = "Impl", entityManagerFactoryRef = "entityManagerFactory", transactionManagerRef = "transactionManager") @EnableTransactionManagement // 啓用事務管理器 public class SpringDataJpaConfig { // 配置jpa廠商適配器(參見spring實戰p320) @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter(); // 設置數據庫類型(可以使用org.springframework.orm.jpa.vendor包下的Database枚舉類) jpaVendorAdapter.setDatabase(Database.MYSQL); // 設置打印sql語句 jpaVendorAdapter.setShowSql(true); // 設置不生成ddl語句 jpaVendorAdapter.setGenerateDdl(false); // 設置hibernate方言 jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect"); return jpaVendorAdapter; } // 配置實體管理器工廠 @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean(); // 注入數據源 emfb.setDataSource(dataSource); // 注入jpa廠商適配器 emfb.setJpaVendorAdapter(jpaVendorAdapter); // 設置掃描基本包 emfb.setPackagesToScan("com.example.entity"); return emfb; } // 配置jpa事務管理器 @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { JpaTransactionManager transactionManager = new JpaTransactionManager(); // 配置實體管理器工廠 transactionManager.setEntityManagerFactory(emf); return transactionManager; } }
啓用web支持還須要在Spring MVC配置類上添加@EnableSpringDataWebSupport
註解mongodb
@Configuration @ComponentScan(basePackages = {"cn.fulgens.controller"}) @EnableWebMvc // 啓用spring mvc @EnableSpringDataWebSupport // 啓用springmvc對spring data的支持 public class WebMvcConfig extends WebMvcConfigurerAdapter { }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
server: port: 8080 servlet: context-path: / spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false username: root password: mysql123 jpa: database: MySQL database-platform: org.hibernate.dialect.MySQL5InnoDBDialect show-sql: true hibernate: ddl-auto: update
ddl-auto數據庫
create
:每次運行程序時,都會從新建立表,故而數據會丟失create-drop
:每次運行程序時會先建立表結構,而後待程序結束時清空表upadte
:每次運行程序,沒有表時會建立表,若是對象發生改變會更新表結構,原有數據不會清空,只會更新(推薦使用)validate
:運行程序會校驗數據與數據庫的字段類型是否相同,字段不一樣會報錯none
: 禁用DDL處理注意:
/src/main/java/com/example/springbootjpa/entity/User package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @Table(name = "tb_user") @Data public class User { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "username", unique = true, nullable = false, length = 64) private String username; @Column(name = "password", nullable = false, length = 64) private String password; @Column(name = "email", length = 64) private String email; }
主鍵採用UUID策略
@GenericGenerator
是Hibernate提供的主鍵生成策略註解,注意下面的@GeneratedValue
(JPA註解)使用generator = "idGenerator"引用了上面的name = "idGenerator"主鍵生成策略
通常簡單的Demo示例中只會使用@GeneratedValue(strategy = GenerationType.IDENTITY)這種主鍵自增的策略,而實際數據庫中表字段主鍵類型不多是int型的
JPA自帶的幾種主鍵生成策略
- TABLE: 使用一個特定的數據庫表格來保存主鍵
- SEQUENCE: 根據底層數據庫的序列來生成主鍵,條件是數據庫支持序列。這個值要與generator一塊兒使用,generator 指定生成主鍵使用的生成器(多是orcale中本身編寫的序列)
- IDENTITY: 主鍵由數據庫自動生成(主要是支持自動增加的數據庫,如mysql)
- AUTO: 主鍵由程序控制,也是GenerationType的默認值
/src/main/java/com/example/springbootjpa/repository/UserRepository package com.example.springbootjpa.repository; import com.example.springbootjpa.entity.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, String> { }
這裏簡單起見省略Service層
/src/main/java/com/example/springbootjpa/controller/UserController package com.example.springbootjpa.controller; import com.example.springbootjpa.entity.User; import com.example.springbootjpa.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Optional; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @PostMapping() public User saveUser(@RequestBody User user) { return userRepository.save(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable("id") String userId) { userRepository.deleteById(userId); } @PutMapping("/{id}") public User updateUser(@PathVariable("id") String userId, @RequestBody User user) { user.setId(userId); return userRepository.saveAndFlush(user); } @GetMapping("/{id}") public User getUserInfo(@PathVariable("id") String userId) { Optional<User> optional = userRepository.findById(userId); return optional.orElseGet(User::new); } @GetMapping("/list") public Page<User> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize)); } }
使用Spring Data建立查詢只需四步:
interface PersonRepository extends Repository<Person, Long> { … }
interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <jpa:repositories base-package="com.acme.repositories"/> </beans>
順帶一提,對於不一樣的Spring Data子項目Spring提供了不一樣的xml命名空間,如對於Spring Data MongoDB能夠將上面的jpa改成mongodb
固然,使用Spring Boot這一步基本能夠省略,咱們須要作的就是在application.properties或application.yml文件中配置幾個屬性便可
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
一種方法是定義一個BaseRepository接口繼承Repository接口,並從CrudRepository中copy你想暴露的CRUD方法src/main/java/com/example/springbootjpa/repository/MyBaseRepository
package com.example.springbootjpa.repository; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.Repository; import java.util.Optional; /** * 自定義Repository,選擇性暴露CRUD方法 * @param <T> * @param <ID> */ @NoRepositoryBean public interface MyBaseRepository<T, ID> extends Repository<T, ID> { Optional<T> findById(ID id); <S extends T> S save(S entity); }
注意:MyBaseRepository上面加了
@NoRepositoryBean
註解
src/main/java/com/example/springbootjpa/repository/UserRepository2
package com.example.springbootjpa.repository; import com.example.springbootjpa.entity.User; import org.springframework.stereotype.Repository; public interface UserRepository2 extends MyBaseRepository<User, String> { }
Junit測試
package com.example.springbootjpa.repository; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Optional; @RunWith(SpringRunner.class) @SpringBootTest public class UserRepository2Test { @Autowired private UserRepository2 userRepositoy; @Test public void findByIdTest() { Optional optional = userRepositoy.findById("40289f0c65674a930165674d54940000"); Assert.assertNotNull(optional.get()); } }
這裏啓動Junit測試時報了一個錯,記錄一下
java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499) ... 50 more
錯誤很明顯Spring應用上下文加載失敗,緣由是找不到javax.xml.bind.JAXBException
手賤從java8升級到java10,JAXB API是java EE 的API,在java SE 9.0 中已經再也不包含這個 Jar 包。java9 中引入了模塊的概念,默認狀況下,Java SE中將再也不包含java EE 的Jar包,而在 java 6/7 / 8 時關於這個API 都是捆綁在一塊兒的,解決方法添加以下jar包
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
解決方法參考自:https://www.cnblogs.com/newcaoguo/p/8831690.html
另外一種方法是使用@RepositoryDefinition
註解,並從CrudRepository中copy你想暴露的CRUD方法src/main/java/com/example/springbootjpa/repository/UserRepository3
package com.example.springbootjpa.repository; import com.example.springbootjpa.entity.User; import org.springframework.data.repository.RepositoryDefinition; import java.util.Optional; @RepositoryDefinition(domainClass = User.class, idClass = String.class) public interface UserRepository3 { Optional<User> findById(String id); User save(User user); }
從Spring Data2.0開始對於返回單個聚合實例的CRUD方法可使用java8 Optional接口做爲方法返回值來代表可能存在的缺省值,典型示例爲CrudRepository的findById方法
另外Spring也提供了幾個註解來處理Null值
@NonNullApi
: 在包級別使用來聲明參數和返回值不能爲Null
@NonNull
: 在參數或返回值上使用,當它們不能爲Null時(若是在包級別上使用了@NonNullApi註解則沒有必要再使用@NonNull註解了)
@Nullable
: 在參數或返回值上使用,當它們能夠爲Null時
Spring Data Jpa經過解析方法名建立查詢,框架在進行方法名解析時,會先把方法名多餘的前綴find…By, read…By, query…By, count…By以及get…By截取掉,而後對剩下部分進行解析,第一個By會被用做分隔符來指示實際查詢條件的開始。 咱們能夠在實體屬性
上定義條件,並將它們與And和Or鏈接起來,從而建立大量查詢:
User findByUsername(String username); List<User> findByUsernameIgnoreCase(String username); List<User> findByUsernameLike(String username); User findByUsernameAndPassword(String username, String password); User findByEmail(String email); List<User> findByEmailLike(String email); List<User> findByIdIn(List<String> ids); List<User> findByIdInOrderByUsername(List<String> ids); void deleteByIdIn(List<String> ids); Long countByUsernameLike(String username);
支持的關鍵字、示例及JPQL片斷以下表所示:
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 | findByFirstname,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 | ... findByFirstnameNotLike |
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<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> ages) | … 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) |
具體Spring Data Jpa對方法名的解析規則可參看官方文檔4.4.3. Property Expressions
Spring Data Jpa支持使用first
、top
以及Distinct
關鍵字來限制查詢結果,如:
User findFirstByUsernameOrderByUsernameAsc(String username); List<User> findTop10ByUsername(String username, Sort sort); List<User> findTop10ByUsername(String username, Pageable pageable);
@Query 註解的使用很是簡單,只需在聲明的方法上面標註該註解,同時提供一個 JPQL 查詢語句便可
@Query("select u from User u where u.email = ?1") User getByEmail(String eamil); @Query("select u from User u where u.username = ?1 and u.password = ?2") User getByUsernameAndPassword(String username, String password); @Query("select u from User u where u.username like %?1%") List<User> getByUsernameLike(String username);
默認狀況下,Spring Data JPA使用基於位置的參數綁定,如前面全部示例中所述。 這使得查詢方法在重構參數位置時容易出錯。 要解決此問題,可使用@Param
註解爲方法參數指定具體名稱並在查詢中綁定名稱,如如下示例所示:
@Query("select u from User u where u.id = :id") User getById(@Param("id") String userId); @Query("select u from User u where u.username = :username or u.email = :email") User getByUsernameOrEmail(@Param("username") String username, @Param("email") String email);
從Spring Data JPA release 1.4開始,Spring Data JPA支持名爲entityName的變量。 它的用法是select x from #{#entityName} x
。 entityName的解析方式以下:若是實體類在@Entity註解上設置了name屬性,則使用它。 不然,使用實體類的簡單類名。爲避免在@Query註解使用實際的實體類名,就可使用#{#entityName}
進行代替。如以上示例中,@Query註解的查詢字符串裏的User均可替換爲#{#entityName}
@Query("select u from #{#entityName} u where u.email = ?1") User getByEmail(String eamil);
@Query註解還支持經過將nativeQuery
標誌設置爲true來執行原生查詢,一樣支持基於位置的參數綁定及命名參數,如:
@Query(value = "select * from tb_user u where u.email = ?1", nativeQuery = true) User queryByEmail(String email); @Query(value = "select * from tb_user u where u.email = :email", nativeQuery = true) User queryByEmail(@Param("email") String email);
注意:Spring Data Jpa目前不支持對原生查詢進行動態排序,但能夠經過本身指定計數查詢
countQuery
來使用原生查詢進行分頁、排序,如:
@Query(value = "select * from tb_user u where u.username like %?1%", countQuery = "select count(1) from tb_user u where u.username = %?1%", nativeQuery = true) Page<User> queryByUsernameLike(String username, Pageable pageable);
Spring Data Jpa能夠在方法參數中直接傳入Pageable
或Sort
來完成動態分頁或排序,一般Pageable或Sort會是方法的最後一個參數,如:
@Query("select u from User u where u.username like %?1%") Page<User> findByUsernameLike(String username, Pageable pageable); @Query("select u from User u where u.username like %?1%") List<User> findByUsernameAndSort(String username, Sort sort);
那調用repository方法時傳入什麼參數呢?
對於Pageable參數,在Spring Data 2.0以前咱們能夠new一個org.springframework.data.domain.PageRequest
對象,如今這些構造方法已經廢棄,取而代之Spring推薦咱們使用PageRequest的of方法
new PageRequest(0, 5); new PageRequest(0, 5, Sort.Direction.ASC, "username"); new PageRequest(0, 5, new Sort(Sort.Direction.ASC, "username")); PageRequest.of(0, 5); PageRequest.of(0, 5, Sort.Direction.ASC, "username"); PageRequest.of(0, 5, Sort.by(Sort.Direction.ASC, "username"));
注意:Spring Data PageRequest的page參數是從0開始的 zero-based page index
對於Sort參數,一樣能夠new一個org.springframework.data.domain.Sort
,但推薦使用Sort.by方法
單獨使用@Query註解只是查詢,如涉及到修改、刪除則須要再加上@Modifying
註解,如:
@Transactional() @Modifying @Query("update User u set u.password = ?2 where u.username = ?1") int updatePasswordByUsername(String username, String password); @Transactional() @Modifying @Query("delete from User where username = ?1") void deleteByUsername(String username);
注意:Modifying queries can only use void or int/Integer as return type!
這裏使用級聯查詢進行多表的關聯查詢
/src/main/java/com/example/springbootjpa/entity/User package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Date; import java.util.Set; import java.util.UUID; @Entity @Table(name = "tb_user") @Data public class User { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "username", unique = true, nullable = false, length = 64) private String username; @Column(name = "password", nullable = false, length = 64) private String password; @Column(name = "email", unique = true, length = 64) private String email; @ManyToMany(targetEntity = Role.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY) @JoinTable(name = "tb_user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")}) private Set<Role> roles; } /src/main/java/com/example/springbootjpa/entity/Role package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; @Entity @Table(name = "tb_role") @Data public class Role { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "role_name", unique = true, nullable = false, length = 64) private String roleName; }
測試
@Test public void findByIdTest() { Optional<User> optional = userRepository.findById("40289f0c65674a930165674d54940000"); Set<Role> roles = optional.get().getRoles(); System.out.println(optional.get()); }
不出意外會報Hibernate懶加載異常,沒法初始化代理類,No Session:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.springbootjpa.entity.User.roles, could not initialize proxy - no Session
緣由:Spring Boot整合JPA後Hibernate的Session就交付給Spring去管理。每次數據庫操做後,會關閉Session,當咱們想要用懶加載方式去得到數據的時候,原來的Session已經關閉,不能獲取數據,因此會拋出這樣的異常。
解決方法:
在application.yml中作以下配置:
@Test public void findByIdTest() { Optional<User> optional = userRepository.findById("40289f0c65674a930165674d54940000"); Set<Role> roles = optional.get().getRoles(); System.out.println(optional.get()); }
/src/main/java/com/example/springbootjpa/entity/Department package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; @Entity @Table(name = "tb_dept") @Data public class Department { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "dept_name", unique = true, nullable = false, length = 64) private String deptName; @OneToMany(mappedBy = "department", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<Employee> employees; } /src/main/java/com/example/springbootjpa/entity/Employee package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.UUID; @Entity @Table(name = "tb_emp") @Data public class Employee { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "emp_name", nullable = false, length = 64) private String empName; @Column(name = "emp_job", length = 64) private String empJob; @Column(name = "dept_id", insertable = false, updatable = false) private String deptId; @ManyToOne(targetEntity = Department.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "dept_id") private Department department; } 測試 @Test public void findByIdTest() { Optional<Employee> optional = employeeRepository.findById("93fce66c1ef340fa866d5bd389de3d79"); System.out.println(optional.get()); }
結果報錯了...
java.lang.StackOverflowError at java.base/java.lang.Exception.<init>(Exception.java:102) at java.base/java.lang.ReflectiveOperationException.<init>(ReflectiveOperationException.java:89) at java.base/java.lang.reflect.InvocationTargetException.<init>(InvocationTargetException.java:73) at jdk.internal.reflect.GeneratedConstructorAccessor54.newInstance(Unknown Source) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:488) at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) at com.mysql.jdbc.PreparedStatement.getInstance(PreparedStatement.java:761) at com.mysql.jdbc.ConnectionImpl.clientPrepareStatement(ConnectionImpl.java:1404) at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4121) at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4025) at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:318) at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:145) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:171) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:147) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.prepareQueryStatement(AbstractLoadPlanBasedLoader.java:226) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:190) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:121) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86) at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87) at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:688) at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75) at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2223) at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:565) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:247) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:430) at com.example.springbootjpa.entity.Department.hashCode(Department.java:14)
經過日誌看sql的輸出,發現了sql重複執行了好屢次。如下我截取了前10條sql記錄。
Hibernate: select employee0_.id as id1_1_0_, employee0_.dept_id as dept_id2_1_0_, employee0_.emp_job as emp_job3_1_0_, employee0_.emp_name as emp_name4_1_0_ from tb_emp employee0_ where employee0_.id=? Hibernate: select department0_.id as id1_0_0_, department0_.dept_name as dept_nam2_0_0_ from tb_dept department0_ where department0_.id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select department0_.id as id1_0_0_, department0_.dept_name as dept_nam2_0_0_ from tb_dept department0_ where department0_.id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=? Hibernate: select employees0_.dept_id as dept_id2_1_0_, employees0_.id as id1_1_0_, employees0_.id as id1_1_1_, employees0_.dept_id as dept_id2_1_1_, employees0_.emp_job as emp_job3_1_1_, employees0_.emp_name as emp_name4_1_1_ from tb_emp employees0_ where employees0_.dept_id=?
經過觀察發現,第一條sql是執行查詢Employee的sql,第二條sql是執行查詢Department的sql,第三條sql是執行Department裏面全部員工的sql,第四條sql是執行查詢Department的sql,後面全部的sql都是執行查詢Department裏面全部員工的sql。
很明顯發生了循環依賴的狀況。這是Lombok的@Data註解的鍋。Lombok的@Data註解至關於@Getter、@Setter、@RequiredArgsConstructor、@ToString、@EqualsAndHashCode這幾個註解。
咱們能夠經過反編譯看一下Lombok生成的toString()方法
// Employee public String toString() { return "Employee(id=" + getId() + ", empName=" + getEmpName() + ", empJob=" + getEmpJob() + ", deptId=" + getDeptId() + ", department=" + getDepartment() + ")"; } // Department public String toString() { return "Department(id=" + getId() + ", deptName=" + getDeptName() + ", employees=" + getEmployees() + ")"; }
能夠發現Lombok爲咱們生成的toString()方法覆蓋了整個類的全部屬性
如今將@Data註解去掉,替換爲@Setter、@Getter、@EqualsAndHashCode,重寫toString()方法
// Department @Override public String toString() { return "Department{" + "id='" + id + '\'' + ", deptName='" + deptName + '\'' + '}'; } // Employee @Override public String toString() { return "Employee{" + "id='" + id + '\'' + ", empName='" + empName + '\'' + ", empJob='" + empJob + '\'' + ", deptId='" + deptId + '\'' + ", department=" + department + '}'; }
再次運行測試用例,測試經過,以上Employee toString()方法打印的department會觸發懶加載,最終日誌輸出的sql以下:
Hibernate: select employee0_.id as id1_1_0_, employee0_.dept_id as dept_id2_1_0_, employee0_.emp_job as emp_job3_1_0_, employee0_.emp_name as emp_name4_1_0_ from tb_emp employee0_ where employee0_.id=? Hibernate: select department0_.id as id1_0_0_, department0_.dept_name as dept_nam2_0_0_ from tb_dept department0_ where department0_.id=? Employee{id='93fce66c1ef340fa866d5bd389de3d79', empName='jack', empJob='hr', deptId='0a4fe7234fff42afad34f6a06a8e1821', department=Department{id='0a4fe7234fff42afad34f6a06a8e1821', deptName='人事部'}}
再來測試查詢Department
@Test public void findByIdTest() { Optional<Department> optional = departmentRepository.findById("0a4fe7234fff42afad34f6a06a8e1821"); Set<Employee> employees = optional.get().getEmployees(); Assert.assertNotEquals(0, employees.size()); }
一樣仍是報了堆棧溢出,錯誤定位在Department和Employee的hashCode()方法上
java.lang.StackOverflowError at com.mysql.jdbc.Util.handleNewInstance(Util.java:439) at com.mysql.jdbc.ResultSetImpl.getInstance(ResultSetImpl.java:342) at com.mysql.jdbc.MysqlIO.buildResultSetWithRows(MysqlIO.java:3132) at com.mysql.jdbc.MysqlIO.getResultSet(MysqlIO.java:477) at com.mysql.jdbc.MysqlIO.readResultsForQueryOrUpdate(MysqlIO.java:3115) at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:2344) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2739) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2486) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:419) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:191) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:121) at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86) at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:87) at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:688) at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:75) at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:2223) at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:565) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:247) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:430) at com.example.springbootjpa.entity.Department.hashCode(Department.java:17)
依舊是Lombok的鍋,@EqualsAndHashCode爲咱們生成的equals()和hashCode()方法會使用全部屬性,注意,Department中employees是Set集合,當咱們調用department.getEmployees()時,Employee的hashCode()方法會被調用,Employee中的hashCode()又依賴於Department的HashCode()方法,這樣又造成了循環引用...
// Department public int hashCode() { int i = 43; String $id = getId(); int result = ($id == null ? 43 : $id.hashCode()) + 59; String $deptName = getDeptName(); result = (result * 59) + ($deptName == null ? 43 : $deptName.hashCode()); Set $employees = getEmployees(); int i2 = result * 59; if ($employees != null) { i = $employees.hashCode(); } return i2 + i; } // Employee public int hashCode() { int i = 43; String $id = getId(); int result = ($id == null ? 43 : $id.hashCode()) + 59; String $empName = getEmpName(); result = (result * 59) + ($empName == null ? 43 : $empName.hashCode()); String $empJob = getEmpJob(); result = (result * 59) + ($empJob == null ? 43 : $empJob.hashCode()); String $deptId = getDeptId(); result = (result * 59) + ($deptId == null ? 43 : $deptId.hashCode()); Department $department = getDepartment(); int i2 = result * 59; if ($department != null) { i = $department.hashCode(); } return i2 + i; }
本身動手重寫equals()和hashCode()方法,去掉@EqualsAndHashCode註解
// Department @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Department that = (Department) o; return Objects.equals(id, that.id) && Objects.equals(deptName, that.deptName); } @Override public int hashCode() { return Objects.hash(id, deptName); } // Employee @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return Objects.equals(id, employee.id) && Objects.equals(empName, employee.empName) && Objects.equals(empJob, employee.empJob) && Objects.equals(deptId, employee.deptId); } @Override public int hashCode() { return Objects.hash(id, empName, empJob, deptId); }
再次運行測試用例,測試經過
總結:慎用@Data註解,使用@Getter、@Setter註解,須要時本身重寫toString()、equals()以及hashCode()方法
參考自官方文檔5.9Auditing
通常數據庫表在設計時都會添加4個審計字段,Spring Data Jpa一樣支持審計功能。Spring Data提供了@CreatedBy
,@LastModifiedBy
,@CreatedDate
,@LastModifiedDate
4個註解來記錄表中記錄的建立及修改信息。
package com.example.springbootjpa.entity; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.Date; import java.util.Set; @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "tb_user") @Data public class User { @Id @GenericGenerator(name = "idGenerator", strategy = "uuid") @GeneratedValue(generator = "idGenerator") private String id; @Column(name = "username", unique = true, nullable = false, length = 64) private String username; @Column(name = "password", nullable = false, length = 64) private String password; @Column(name = "email", unique = true, length = 64) private String email; @ManyToMany(targetEntity = Role.class, cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "tb_user_role", joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id")}) private Set<Role> roles; @CreatedDate @Column(name = "created_date", updatable = false) private Date createdDate; @CreatedBy @Column(name = "created_by", updatable = false, length = 64) private String createdBy; @LastModifiedDate @Column(name = "updated_date") private Date updatedDate; @LastModifiedBy @Column(name = "updated_by", length = 64) private String updatedBy; }
實體類上還添加了
@EntityListeners(AuditingEntityListener.class)
,而AuditingEntityListener是由Spring Data Jpa提供的
光添加了4個審計註解還不夠,得告訴程序究竟是誰在建立和修改表記錄/src/main/java/com/example/springbootjpa/auditing/AuditorAwareImpl
package com.example.springbootjpa.auditing; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; import java.util.Optional; @Component public class AuditorAwareImpl implements AuditorAware<String> { @Override public Optional<String> getCurrentAuditor() { return Optional.of("admin"); } }
這裏簡單的返回了一個"admin"字符串來表明當前用戶名
在Spring Boot啓動類上添加@EnableJpaAuditing
註解用於啓用Jpa的審計功能
package com.example.springbootjpa; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @SpringBootApplication @EnableJpaAuditing public class SpringBootJpaApplication { public static void main(String[] args) { SpringApplication.run(SpringBootJpaApplication.class, args); } }
更多關於Jpa Specifications、Example查詢請查閱官方文檔
參考資料:
Spring Data Jpa官方文檔
使用Hibernate、JPA、Lombok遇到的有趣問題
SpringData Jpa、Hibernate、Jpa 三者之間的關係
Spring Data-JPA versus JPA: What's the difference?