我们使用 spring-data jpa 和 hibernate 实现。
我有一个父实体,其中包含子实体列表。获取类型是惰性的。当我在服务类中调用 find 方法时。我取回了父对象,但在子对象列表上执行 size() 给了我惰性异常:
failed to lazily initialize a collection of role: could not initialize proxy - no Session
既然我的 find 方法上有 @Transacitonal 注释,我是否应该能够在延迟加载的列表上执行 size() 操作?
@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
}
最佳答案
仅当您配置 Spring Transaction Manager 时,@Transactional 才会将您的方法调用包装在事务中。
假设您已经使用 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);
}
}
关于java - 在延迟加载列表上调用 size() 时无法延迟初始化集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352712/