gpt4 book ai didi

java - LazyInitializationException 与 @Any(fetch = FetchType.EAGER) 和 Spring-boot

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:01 24 4
gpt4 key购买 nike

尽管有“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;
}

}

关于java - LazyInitializationException 与 @Any(fetch = FetchType.EAGER) 和 Spring-boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24286475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com