JPA中的could not initialize proxy
阿新 • • 發佈:2019-01-04
引言: JPA是一種非常流行和常用的持久化框架標準,其下可以對接若干種不同的實現,在不同的父子表管理中,經常會碰到no Session的問題,該如何解決呢?
1. 問題的引出
在進行基於JPA的單元測試中,我們使用JUnit來進行測試資料庫的關聯表資訊讀取,結果得到如下錯誤資訊:
經過分析,其中的關鍵詞是: could not initialize proxy - no Session; 基於JPA的實現來分析,就是在進行資料庫訪問之時,當前針對資料庫的訪問與操作session已經關閉且釋放了,故提示no Session可用。org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.rain.wx.meal.model.DishCategory.dishes, could not initialize proxy - no Session at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587) at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:204) at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:566) at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:135) at org.hibernate.collection.internal.PersistentBag.get(PersistentBag.java:449) at com.rain.wx.meal.service.DishServiceTest.testDishes(DishServiceTest.java:86) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
2. 程式碼實現分析
讓我們來看看具體的程式碼吧
另外一個實體Bean為MealDish, 其程式碼為:@Entity @Table(name="dish_category") @Data @EqualsAndHashCode(callSuper=false) @JsonRootName(value="category") public class DishCategory extends BaseEntity { private static final long serialVersionUID = -7189824224534351030L; @Column private String name; @Column private String description; @OneToMany @JoinColumn(name="category_id",referencedColumnName="id") private List<MealDish> dishes; }
其中Repository/Service的程式碼分別如下:@Entity @Table(name = "dish") @JsonRootName(value="dish") //@Lazy(value=false) public class MealDish extends BaseEntity { private static final long serialVersionUID = -3982356728880195795L; @Column private String name; @Column private float price; @Column(name = "img_url") private String imgUrl; @Column(name="category_id") private long categoryId; @Column private boolean active; // 銷售數量 @Column private int soldCount; ....... }
@Service
public class DishServiceImpl implements DishService {
@Transactional
@Override
public List<DishCategory> getDishCategory() {
return this.dishCategoryRepo.findAll();
}
........
}
Repository相關的程式碼都是空程式碼,無實際的實現,這裡再次忽略。單元測試的程式碼內容:
@Test
public void testDishes() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
List<DishCategory> categories = this.dishService.getDishCategory();
for (DishCategory category : categories) {
// log.debug(String.valueOf(category.getDishes().get(0)));
}
String jsonStr = mapper.writeValueAsString(categories);
log.info(jsonStr);
}
3. 問題分析基於對Hibernate和JPA的理解,在ORM中,其為了提升效能使用了Lazy載入,就是在使用的時候,才會載入額外的資料,故導致了在使用之時再載入資料之時, session失效的問題出現。所以問題的目標點實現提前載入資料。
4. 問題的解決
嘗試1: 在Service方法中新增了@Transactional進行事務新增
結果1: 無效
嘗試2: 在@OneToMany的方法上,使用@Lazy(false)
結果2: 無效
嘗試3: 在@OneToMany的引數中使用fetch=FetchType=Eager
結果3: 問題解決
嘗試4: 在application.properties的配置檔案中新增spring.jpa.open-in-view=true
結果4: 問題解決
方法3的正確的程式碼內容:
@Entity
@Table(name="dish_category")
@Data
@EqualsAndHashCode(callSuper=false)
@JsonRootName(value="category")
public class DishCategory extends BaseEntity {
private static final long serialVersionUID = -7189824224534351030L;
@Column
private String name;
@Column
private String description;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="category_id",referencedColumnName="id")
private List<MealDish> dishes;
}
方法4的解釋與說明:
這個設定選項:
spring.jpa.open-in-view=true其實是之前的openEntityManagerInViewInterceptor,解決在Spring MVC與JPA之間Session的宣告週期問題
5. 總結
核心問題在於解決延遲載入為及時載入,及時載入會消耗一定的資源,將其程式的效能,請注意這個問題。