2016-12-27 76 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