我有一個數據庫,其中用戶和地址數據存儲在單獨的表中。當用戶登錄到我的頁面時,我想向他顯示一個可以更改其用戶/帳戶數據的表單。但是,我最終得到一個例外: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);
}
爲什麼不這項工作?爲什麼它對用戶數據有效?
老天的OpenSessionInView模式, – jFrenetic
是否使用Spring聲明式事務,如果你是那麼你可以這樣'.Net'編碼風格傷眼睛=)檢查(addressService)是否有方法或類級別的@Transaction註釋? –