JPA懒惰提取不起作用并抛出LazyInitializationException

Pra*_*ain 2 java spring hibernate jpa hibernate-mapping

我是一个新的蜜蜂来弹出数据JPA,所以我试图用它来制作一些东西,这样我就可以知道如何获取模式,但它会抛出异常,请查看代码.

public class State {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

  String name;

  @OneToMany(mappedBy = "state", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  Set<Constituency> constituencies ;

  public void fetchLazyCollection() {
    getConstituencies().size();
  }
}

public class Constituency {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

  String name;

  @ManyToOne
  @JoinColumn(name = "state_id")
  State state;
}
Run Code Online (Sandbox Code Playgroud)

所以,正如你所看到的,有两个类StateConstituency,从StateConstituency,一对多映射存在,反之亦然,有多对一.如果我在这里犯了任何愚蠢的错误,请告诉我.

@Test
public void delhiShouldHaveTwoConstituency(){
  State delhi = new State();
  delhi.setName("New Delhi");

  Constituency northWest = new Constituency();
  northWest.setName("North West");
  northWest.setState(delhi);

  Constituency southDelhi = new Constituency();
  southDelhi.setName("South Delhi");
  southDelhi.setState(delhi);

  Set<Constituency> constituencies = new HashSet<Constituency>();
  constituencies.add(northWest);
  constituencies.add(southDelhi);

  delhi.setConstituencies(constituencies);

  stateRepository.save(delhi);

  List<State> states= stateRepository.findByName("New Delhi");
  states.get(0).fetchLazyCollection();
  assertThat(delhi.getConstituencies().size(), is(2));
}
Run Code Online (Sandbox Code Playgroud)

现在,我有一个测试,它正在保存一个有两个选区的州,然后我试图再次使用以下方法检索它们:

List<State> states= stateRepository.findByName("New Delhi");
Run Code Online (Sandbox Code Playgroud)

按照我的理解,我假设,因为这语句将执行,选区国家不会得到使用,直到下一个语句执行是调用fetchLazyCollectionfetchLazyCollection调用它抛出的异常

无法初始化代理 - 无会话

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.prateekj.model.State.constituencies, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:567)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:187)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:138)
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:156)
at com.prateekj.model.State.fetchLazyCollection(State.java:35)
at com.prateekj.repositories.StateRepositoryTest.shouldDoIt(StateRepositoryTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:65)
Run Code Online (Sandbox Code Playgroud)

正如我所假设的,每个单元测试在java中维护自己与数据库交互的会话,可能是我错了,谁能告诉我我在这里做了什么错?任何帮助将不胜感激.

Vla*_*cea 6

你得到一个LazyInitializationException因为stateRepository.findByName("New Delhi")是打开/关闭事务/会话的那个,因此你无法在正在运行的Hibernate之外获取额外的关联Session.

添加@Transactional到您的测试将解决此问题,您不必调用:

states.get(0).fetchLazyCollection();
Run Code Online (Sandbox Code Playgroud)

如果你总是想要获取Constituencies状态,你应该有类似的东西:

select s from State s left join fetch s.constituencies where s.name = :stateName
Run Code Online (Sandbox Code Playgroud)