尽管有“fetch = FetchType.EAGER”,但我遇到了常见异常“org.hibernate.LazyInitializationException:无法初始化代理 - 无 session ”,我可以't(不想)手动管理hibernate session (我使用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}
B 型看起来像 A 型:
@Entity
public class TypeA implements CommonType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private double param=0;
//getters and setters
}
以及 Holder 的存储库:
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 的问题,但我无法处理它。提前致谢!
这不是一个好的解决方案,但它确实有效。但我想得到一个更好的。它是带有 @Transactional 和 Hibernate.initialize 的服务:
@Component
@Transactional
public class ServiceHolder {
@Autowired
HolderRepository holderRepository;
public Holder getH(long id) {
Holder holder = holderRepository.findOne(id);
Hibernate.initialize(holder.getType());
return holder;
}
}
我是一名优秀的程序员,十分优秀!