我是一个用于弹出数据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");
根据我的理解,我假设当这个陈述将执行时,州中的选区不会获得初始化,直到下一个语句执行即将调用< strong> fetchLazyCollection 但是当 fetchLazyCollection 调用它时抛出异常
无法初始化代理 - 无会话
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中的每个单元测试都维护着自己与数据库交互的会话,可能是我错了,有谁能告诉我我在这里做了什么错? 任何帮助将不胜感激。
答案 0 :(得分:6)
您得到LazyInitializationException
因为stateRepository.findByName("New Delhi")
是打开/关闭事务/会话的人,因此您无法在正在运行的Hibernate Session
之外获取其他关联。
在测试中添加@Transactional
可解决此问题,您无需致电:
states.get(0).fetchLazyCollection();
如果你总是希望用状态获取Constituencies
,你应该有类似的东西:
select s from State s left join fetch s.constituencies where s.name = :stateName
答案 1 :(得分:0)
延迟加载在持久化上下文中工作。当您的交易完成后,您无法执行延迟提取。您可以扩展事务范围,以便在事务中获取集合,或创建将为您返回集合的查询。另一种方法是在一个stareRepository方法中手动获取集合,例如List<State> states = stateRepository.findByNameAndFetchCollection("New Delhi");
,其中事务应该仍处于活动状态。
答案 2 :(得分:0)
这是因为您在事务(会话)之外获取延迟集合。所以你有两种方法:
设置hibernate属性(对于SessionFactory),它允许非事务性加载lazies:
&lt; prop key =&#34; hibernate.enable_lazy_load_no_trans&#34;&gt; true&lt; / prop&gt;
答案 3 :(得分:0)
将延迟标记设置为true,如下所示
@OneToMany(mappedBy = "objectId", cascade = CascadeType.ALL, orphanRemoval = true , fetch = FetchType.EAGER)