2011-12-08 61 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

您可以考虑使用,即使它并不总是最好的解决办法