2014-06-18 72 views
1

我有一個共同的例外「org.hibernate.LazyInitializationException:無法初始化代理 - 沒有會話」儘管「取= FetchType.EAGER「,我不能(不想)手動管理hibernate會話(我使用Spring-Boot-starter-data-jpa)。LazyInitializationException中與@Any(取= FetchType.EAGER)和Spring啓動

我有一個希爾德實體,包含CommonType的財產(TapeA或類型B):

@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看起來像類型A:

@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的問題,但我無法處理它。 在此先感謝!

回答

0

這不是最好的解決方案,但它的工作原理。但我想變得更好。 它是服務與@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; 
} 

}

相關問題