JPA存储库org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话

时间:2015-11-02 20:58:05

标签: java hibernate jpa spring-data spring-transactions

我有以下模型实体:

@Entity
@Table(name="ABONADO_IMEI")
public class SubscriberImei {
    private SubscriberImeiId id;
    private Terminal terminal;
    private String state;
    private Date date;

    @EmbeddedId
    public SubscriberImeiId getId() {
        return id;
    }
    public void setId(SubscriberImeiId id) {
        this.id = id;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ID_TERMINAL", nullable=false)
    public Terminal getTerminal() {
        return terminal;
    }
    public void setTerminal(Terminal terminal) {
        this.terminal = terminal;
    }

    @Column(name="Estado")
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }

    @Column(name="Fecha")
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }

}

@Entity()
public class Terminal {
    private long id;
    private String code;
    private String brand;
    private String model;
    private String services;
    private Set<SubscriberImei> subscriberImei;

    public Terminal(){

    }

    @Id
    @SequenceGenerator(name="SEQ_TERMINAL_ID", sequenceName="SEQ_TERMINAL_ID",allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "SEQ_TERMINAL_ID")
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column(name="Codigo")
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Column(name="Marca")
    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Column(name="Modelo")
    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    @Column(name="Servicios")
    public String getServices() {
        return services;
    }

    public void setServices(String services) {
        this.services = services;
    }

    @OneToMany(fetch=FetchType.LAZY , mappedBy="terminal")
    public Set<SubscriberImei> getSubscriberImei() {
        return subscriberImei;
    }
    public void setSubscriberImei(Set<SubscriberImei> terminals) {
        this.subscriberImei = terminals;
    }   
}

我正在使用以下JPARepository来访问它:

public interface SubscriberImeiDao extends JpaRepository<SubscriberImei, SubscriberImeiId>{
    @Query("select u from SubscriberImei u where u.id.snb = ?1 and u.state = ?2")
    SubscriberImei findBySnbAndState(String snb, String state);
}

我需要返回findBySnbAndState的结果。这是我的代码:

@Transactional
public SubscriberImei imeiQuery(String countryId, String snb) {
    SubscriberImei subs = null;

    try{
        this.validateRegion(countryId, snb);

        subs = this.getSubscriberDao().findBySnbAndState(snb,"A");
        subs.getTerminal().getBrand();
        if( subs != null)
            log.info("Subscriber found {}", subs);
        else
            log.info("Subcriber not found!");
    } catch (Exception ex) {
        log.error("Unknown Exception -- ", ex);
    }
    return subs;
}

我在sub.getTerminal()。getBrand()行中得到了提到的异常。通过这条线,我强迫我们遵循懒惰的关系(正如其他一些问题所建议的那样)。我还在我的上下文中添加了以下行:

<tx:annotation-driven mode="aspectj"/>

将FetchType更改为Eager使其工作,但我不想这样做,因为没有必要始终遵循关系。我错过了什么?我做错了什么?

由于

这是完整的异常堆栈跟踪

 org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at ar.com.redmondsoftware.imeitracking.model.Terminal_$$_jvste48_0.getBrand(Terminal_$$_jvste48_0.java)
    at ar.com.redmondsoftware.imeitrackingbusinesslogic.service.impl.ImeiQueryImpl.imeiQuery(ImeiQueryImpl.java:24)
    at ar.com.redmondsoftware.imeitracking.QueryImei.testQueryImei(QueryImei.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

1 个答案:

答案 0 :(得分:1)

如果您不希望它一直渴望获取,您可以在需要时创建另一个执行急切获取的查询:

@Query("SELECT u FROM SubscriberImei u LEFT JOIN FETCH u.terminal WHERE u.id.snb = ?1 and u.state = ?2")
SubscriberImei findBySnbAndStateWithTerminal(String snb, String state);

此查询几乎总是首选,因为它将使用一个查询而不是两个查询加载数据。