gpt4 book ai didi

java - JPA 延迟获取不起作用并抛出 LazyInitializationException

转载 作者:行者123 更新时间:2023-12-01 12:28:04 25 4
gpt4 key购买 nike

我是 spring 数据 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;
}

因此,如您所见,有两个类 国家选区来自 国家选区存在一对多映射,反之亦然存在多对一映射。
如果我在这里犯了任何愚蠢的错误,请告诉我。
@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));
}

现在,我有一个测试,它正在保存一个具有两个选区的州,然后我尝试使用以下方法再次检索它们:
List<State> states= stateRepository.findByName("New Delhi");

根据我的理解,我假设这条语句会执行, 选区国家在下一条语句执行之前不会被初始化,该语句将调用 fetchLazyCollection 但作为 fetchLazyCollection 调用它抛出异常

无法初始化代理 - 无 session
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)

正如我假设的那样,Java 中的每个单元测试都维护自己的与数据库交互的 session ,可能是我错了,有人能告诉我我在这里做错了什么吗?
任何帮助将不胜感激。

最佳答案

您会收到 LazyInitializationException因为在你走出stateRepository.findByName("New Delhi")之后, hibernate Session关闭,并且您无法在正在运行的 Hibernate 之外获取其他关联 Session .
添加 @Transactional到您的测试将解决此问题,您不必调用:

states.get(0).fetchLazyCollection();
最好在原始实体查询中获取您需要的惰性关联:
select s 
from State s
left join fetch s.constituencies
where s.name = :stateName

关于java - JPA 延迟获取不起作用并抛出 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23923886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com