2016-12-27 75 views
0

我们在hibernate实现中使用spring-data jpa。在懒惰的加载列表上调用size()时,懒惰地初始化一个集合

我有一个拥有子列表的父实体。提取类型很懒。当我在我的服务类中调用find方法时。我得到的父对象回来,但孩子的名单上做的大小()给了我懒惰的例外:

failed to lazily initialize a collection of role: could not initialize proxy - no Session 

我不应该能够将延迟加载列表上做的大小(),因为我找到方法@它的交易注释?

@Entity 
    @Table(name="PARENT") 
    public class Parent implements Serializable{ 

    @OneToMany(targetEntity = Child.class, cascade=CascadeType.ALL, orphanRemoval=true) 
    @JoinColumn(name="pk", insertable=false, updatable=false, nullable=false) 
    private List<Child> children; 

} 


    @Entity 
    @Table(name="CHILD") 
    public class Child implements Serializable { 
    private static final long serialVersionUID = -3574595532165407670L; 

    @Id 
    @Column(name = "pk") 
    @SequenceGenerator(name="childPK_GENERATOR", sequenceName="childseq") 
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="childPK_GENERATOR") 
    private Long pk; 
} 

服务类:

@Transactional 
    public Parent find(Lond id){ 
     Parent parent = parentRepository.findOne(id) 
     parent.getChildren.size(); //throws lazy load exception 
    } 

回答

1

@Transactional将包裹你的方法调用只有当你已配置 Spring的事务管理器的事务。

假设您已经用java配置文件配置了JPA。

@Import(TransactionConfig.class) 
public class JpaConfig { 
// your EntityManagerFactory configs... 
} 

那么你应该配置事务管理

@Configuration 
@EnableTransactionManagement 
public class TransactionConfig { 

    @Bean 
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { 
     return new JpaTransactionManager(emf); 
    } 
} 
+0

我们确实启用了Spring的事务管理器。我们没有使用java配置,而是使用xml配置来这样做: '' – Nero

+0

@Nero当你得到延迟初始化异常时,它意味着你的实体'parent'处于** detached **状态。 - >这意味着**持久性上下文关闭**,在方法'parentRepository.findOne(id)'调用之后。 - >因此,在调用find方法时没有创建spring事务**。 _因此,事务管理器未启用,或者配置错误_ – Taras