我有一个数据库,其中用户和地址数据存储在单独的表中。当用户登录到我的页面时,我想向他显示一个可以更改其用户/帐户数据的表单。但是,我最终得到一个例外: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注释? –