【发布时间】:2014-08-08 19:17:10
【问题描述】:
尽管有“fetch = FetchType.EAGER”,但我遇到了一个常见异常“org.hibernate.LazyInitializationException: could not initialize proxy - no Session”,我可以't(不想)手动管理休眠会话(我使用 Spring-Boot-starter-data-jpa)。
我有一个 Hilder 实体,它包含 CommonType(TapeA 或 TypeB)的属性:
@Entity
public class Holder<T extends CommonType> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Any(metaColumn = @Column(name = "type", nullable = false), optional = false, fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.ALL )
@AnyMetaDef(
idType = "long",
metaType = "string",
metaValues = {
@MetaValue(value = "TypeA", targetEntity = TypeB.class),
@MetaValue(value = "TypeB", targetEntity = TypeA.class)
})
@JoinColumn(name = "property_id", nullable = false)
private T type;
//getters and setters}
TypeB 看起来像 TypeA:
@Entity
public class TypeA implements CommonType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private double param=0;
//getters and setters
}
以及持有人的存储库:
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface HolderRepository extends CrudRepository<Holder, Long> {
}
跑步者:
@Configuration
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class);
HolderRepository repository = context.getBean(HolderRepository.class);
TypeA simpleDeviceState = new TypeA();
Holder<TypeA> holder = new Holder<>(simpleDeviceState);
repository.save(holder);
Holder holder1=repository.findAll().iterator().next();
TypeA typeA= (TypeA) holder1.getType();
System.out.println("Param: "+typeA.getParam());
context.close();
}}
Pom 仅包含 org.springframework.boot::spring-boot-starter-data-jpa 和 com.h2database::h2。
在打印点出现异常。我想我得到 org.hibernate.LazyInitializationException 因为 fetch = FetchType.EAGER 不起作用。
级联也仅适用于 PERSIST。 也许混合 Hibernate 和 JPA 的问题,但我无法处理。 提前致谢!
【问题讨论】:
标签: java hibernate jpa spring-data-jpa