2017-05-08 158 views
0

我是Hibernate的新手,在尝试从= n实体模型中获取集合时出现以下错误,转换导致错误:未能懒惰地初始化一个角色集合:无法初始化代理 - 没有会话

发生错误导致转换:无法初始化懒洋洋角色的集合:[...]无法初始化代理 - 没有会话

我试着加入@Transactional但我避风港没有任何成功。

相关代码:

Policy.java

@Entity 
@Table(name = "policy") 
public class Policy { 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 
    @OneToMany(mappedBy = "policy") 
    private Set<Item> items = new HashSet<>(); 
    ... 
} 

IntercomApiImpl

@Component 
public class IntercomApiImpl implements IntercomApi { 
    private final String apiToken; 
    private final PolicyFeeDao policyFeeDao; 
    private final SimpleDateFormat dobFormat; 

    @Autowired 
    public IntercomApiImpl(@Qualifier("intercomApiToken") String apiToken, 
     PolicyFeeDao policyFeeDao) { 
     this.apiToken = apiToken; 
     Intercom.setToken(this.apiToken); 
     this.policyFeeDao = policyFeeDao; 
     this.dobFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    } 

    private Map<String, CustomAttribute> getPolicyAttrs(Policy policyToPay) { 
     Map<String, CustomAttribute> customAttrs = Maps.newHashMap(); 
     Set<Item> items = policyToPay.getItems(); 

     customAttrs.put("item_count", 
     CustomAttribute.newIntegerAttribute("item_count", items.size())); 

     return customAttrs; 
    } 
} 

我也有这个设置(我不知道这是有关):

@Bean 
public LocalSessionFactoryBean sessionFactoryBean() { 
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); 
    sessionFactoryBean.setDataSource(dataSource()); 
    sessionFactoryBean.setPackagesToScan("com.app.model"); 
    sessionFactoryBean.setHibernateProperties(hibernateProperties()); 
    return sessionFactoryBean; 
} 

protected Properties hibernateProperties() { 
    Properties properties = new Properties(); 
    properties.setProperty("hibernate.dialect", getProperty("hibernate.dialect")); 
    return properties; 
} 

@Bean 
public HibernateTransactionManager transactionManager() { 
    return new HibernateTransactionManager(sessionFactoryBean().getObject()); 
} 

我已经尝试将@Transactional添加到getPolicyAttrs(),但没有奏效。任何想法我失踪?

回答

0

@Transactional在这种情况下不起作用,因为您没有在此方法中获取策略,而是将其作为参数传递给它。

您可以将您的OneToMany关系更改为EAGER,以便子对象始终与父代一起提取,但这可能会导致性能问题。如果你想保持它的懒惰,你将不得不在延迟集合显式调用初始化它,使用Hibernate.initialize()

Hibernate.initialize(policyToPay.getItems()); 
相关问题