2012-03-01 92 views
2

我使用Spring 3.0.5,Hibernate 3.6.7和Vaadin。休眠「沒有會話或會話已關閉」即使會話綁定在事務性方法

我有一個簡單的實體就是這個樣子

@Entity 
public class Foo { 
    @OneToMany(fetch = FetchType.LAZY) 
    private Collection<Bar> bars; 
    ... 
} 

我有一個對話窗口,我從上下文中獲取和它應該表現出從「富」的「棒」。

@Component 
@Scope("prototype") 
public class FooBarDialogImp extends Window implements FooBarDialog { 
    @Transactional(readOnly = true) 
    public void populate(Foo foo) { 
     ... 
     for (Bar bar : foo.getBars()) { 
      // populate the dialog with bar information 
      ... 
     } 
    } 
} 

而當用戶詢問展現出富吧,我做這樣的事情

public class FooController { 
... 
    public void showFooBars(Foo foo) { 
     FooBarDialog dialog = context.getBean(FooBarDialog.class); 

     dialog.populate(foo); 
     showDialog(dialog); 
    } 
} 

但問題是,我從休眠「無會話」的異常。我改變了代碼注入會話工廠,看看是否有綁定的會話,它是。我不知道我做錯了什麼。任何人有想法?

回答

8

您將集合的關聯類型指定爲LAZY,因此只有在擁有對象的getter方法被調用時纔會加載。要做到這一點的警告是,它需要在會議的範圍內,無論是創建它還是新的會議。而使用新會話來加載懶惰列表的警告是,您的實體被認爲是與它分離的,並且在可以調用以獲得懶惰集合之前,首先需要爲merged

所以只要致電:

session.merge(foo); 

之前試圖重複其bars

+0

真棒。我沒有想到實體正在脫離會話。你的回答讓我們找到了更好的解決方案。謝謝 :) – 2012-03-01 20:56:02