2011-12-08 60 views
0

我有一個數據庫,其中用戶和地址數據存儲在單獨的表中。當用戶登錄到我的頁面時,我想向他顯示一個可以更改其用戶/帳戶數據的表單。但是,我最終得到一個例外:org.hibernate.LazyInitializationException: could not initialize proxy - no Session。地址屬性無法加載。用戶加載得很好,這就是我不明白的地方。我AddressDAOImpl看起來是這樣的:Hibernate LazyInitializationException - 如何解決此問題?

@Autowired 
private SessionFactory sessionFactory; 
public void addAddress(Address address) 
{ 
     sessionFactory.getCurrentSession().save(address); 
} 
public void updateAddress(Address address) 
{ 
    sessionFactory.getCurrentSession().update(address);  
} 
public List<Address> listAddress() 
{ 
    return sessionFactory.getCurrentSession().createQuery("from address").list(); 
} 
public void deleteAddress(int id) 
{ 
    Address addr = (Address) sessionFactory.getCurrentSession().load(Address.class, id); 
    if(addr != null) 
    { 
     sessionFactory.getCurrentSession().delete(addr); 
    } 
} 
public Address getAddress(int id) 
{ 
     return (Address) sessionFactory.getCurrentSession().load(Address.class, id);  
} 

我的控制器做到這一點:

@RequestMapping("/library/home") 
public ModelAndView showHome() 
{ 
    String username = SecurityContextHolder.getContext().getAuthentication().getName(); 
    User user = userService.getUser(username); 
    Address address = addressService.getAddress(user.getId()); 
    ModelMap mmap = new ModelMap(); 
    mmap.addAttribute("user", user); 
    mmap.addAttribute("addresse", address); 
    return new ModelAndView("/library/home", mmap); 
} 

爲什麼不這項工作?爲什麼它對用戶數據有效?

+0

老天的OpenSessionInView模式, – jFrenetic

+0

是否使用Spring聲明式事務,如果你是那麼你可以這樣'.Net'編碼風格傷眼睛=)檢查(addressService)是否有方法或類級別的@Transaction註釋? –

回答

2

我假設你AddressService創建用於加載地址代理交易(這是一個代理,因爲你使用的load()不是GET的())。當您從AddressService返回地址時,與此事務關聯的會話將關閉。

當您的視圖解析器嘗試訪問Address代理的屬性時,沒有會話可用於通過它運行數據庫查詢來獲取屬性。因此例外。

可以使用get()而不是load(),或者在仍處於事務處理範圍時訪問屬性。

+1

謝謝。使用get()而不是load()修復了我的問題。 – tschaei

+0

警告:如果您在獲得代理之前進行了獲取並獲得了某個地方,那麼如果它位於緩存中,您仍然可以獲得代理服務器! – wwadge

0

我認爲它可能是因爲你沒有初始化SessionFactory的配置。試試這個課程來幫助你創建一個會話工廠。

import org.hibernate.SessionFactory; 
import org.hibernate.cfg.Configuration; 


public class HibernateUtil { 
private static final SessionFactory sessionFactory;  
static {   
    try {   
     sessionFactory = new Configuration().configure()     
     .buildSessionFactory();  
    } catch (Throwable ex) {   
     System.err.println("Initial SessionFactory creation failed." + ex);   
     throw new ExceptionInInitializerError(ex);  
    } 
} 

public static SessionFactory getSessionFactory() { 
    return sessionFactory; 
} 

} 

希望這有助於

0

您可以考慮使用,即使它並不總是最好的解決辦法