I got a common exception " org.hibernate.LazyInitializationException: could not initialize proxy - no Session " in spite of " fetch = FetchType.EAGER " and I can't (wan't) manage hibernate session manually (I use Spring-Boot-starter-data-jpa).
I have a Hilder entity, that contains property of CommonType (TapeA or 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 looks like TypeA:
@Entity
public class TypeA implements CommonType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private double param=0;
//getters and setters
}
And repository for Holder :
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface HolderRepository extends CrudRepository<Holder, Long> {
}
Runner:
@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 contain org.springframework.boot::spring-boot-starter-data-jpa and com.h2database::h2 only.
In printing point exception appears. I guess that I get org.hibernate.LazyInitializationException because fetch = FetchType.EAGER does't work.
Also cascading works for PERSIST only. Maybe the problem in mixing Hibernate and JPA, but I can not handle it. Thanks in advance!
It is not the good solution, but it works. But I would like to get better one. It is service with @Transactional and 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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.