休眠没有会话(没有依赖关系)

时间:2014-11-14 15:30:29

标签: java hibernate

我有以下JPA实体(使用Netbeans生成):

package com.tsystems.tf.db.models;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author johorvat
 */
@Entity
@Table(name = "TABLE1")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Testcase.findAll", query = "SELECT t FROM Testcase t")
})
public class Testcase implements Serializable {
    private static final long serialVersionUID = 1L;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Id
    @Basic(optional = false)
    @Column(name = "TESTCASE_ID")
    private BigDecimal testcaseId;
    @Basic(optional = false)
    @Column(name = "TESTCASE_NAME")
    private String testcaseName;
    @Basic(optional = false)
    @Column(name = "CREATOR")
    private String creator;
    @Basic(optional = false)
    @Column(name = "CREATED_AT")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Column(name = "LAST_RUN")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastRun;
    @Column(name = "LAST_RUN_RESULT")
    private Character lastRunResult;
    @Column(name = "INPUT")
    private String input;
    @Column(name = "OUTPUT")
    private String output;

    public Testcase() {
    }

    public Testcase(BigDecimal testcaseId) {
        this.testcaseId = testcaseId;
    }

    public Testcase(BigDecimal testcaseId, String testcaseName, String creator, Date createdAt) {
        this.testcaseId = testcaseId;
        this.testcaseName = testcaseName;
        this.creator = creator;
        this.createdAt = createdAt;
    }

    public BigDecimal getTestcaseId() {
        return testcaseId;
    }

    public void setTestcaseId(BigDecimal testcaseId) {
        this.testcaseId = testcaseId;
    }

    public String getTestcaseName() {
        return testcaseName;
    }

    public void setTestcaseName(String testcaseName) {
        this.testcaseName = testcaseName;
    }

    public String getCreator() {
        return creator;
    }

    public void setCreator(String creator) {
        this.creator = creator;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getLastRun() {
        return lastRun;
    }

    public void setLastRun(Date lastRun) {
        this.lastRun = lastRun;
    }

    public Character getLastRunResult() {
        return lastRunResult;
    }

    public void setLastRunResult(Character lastRunResult) {
        this.lastRunResult = lastRunResult;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getOutput() {
        return output;
    }

    public void setOutput(String output) {
        this.output = output;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (testcaseId != null ? testcaseId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Testcase)) {
            return false;
        }
        Testcase other = (Testcase) object;
        if ((this.testcaseId == null && other.testcaseId != null) || (this.testcaseId != null && !this.testcaseId.equals(other.testcaseId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.tsystems.tf.db.models.Testcase[ testcaseId=" + testcaseId + " ]";
    }

}

我尝试使用Hibernate为这个实体实现CRUD操作,但是我得到了LazyEvaluationException。没有参考。它在数据库中只有1个表...我可以查询但是当我尝试发布更新时,异常被抛出。现在我有一个非常天真的实现,如下所示:

package com.tsystems.tf.dao.impl;

import com.tsystems.tf.dao.ITestcaseDAO;
import com.tsystems.tf.db.models.Testcase;
import java.math.BigDecimal;
import java.util.Collection;
import javax.transaction.Transactional;
import org.apache.catalina.tribes.util.Arrays;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.jboss.logging.Logger;

public class TestcaseDAOImpl implements ITestcaseDAO {

    private static final SessionFactory sessionFactory;

    static {
        Configuration configuration = new Configuration();
        configuration = configuration.configure();

        StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
        registryBuilder = registryBuilder.applySettings(configuration.getProperties());

        StandardServiceRegistry registry = registryBuilder.build();
        sessionFactory = configuration.buildSessionFactory(registry);
    }

    @Override
    public Collection<Testcase> getAllTestcase() {
        Session session = sessionFactory.openSession();
        Transaction transaction = null;

        Collection<Testcase> testcaseCollection = null;

        try {
            transaction = session.beginTransaction();

            Query query = session.getNamedQuery("Testcase.findAll");
            testcaseCollection = query.list();

            transaction.commit();
        } catch (final HibernateException ex) {
            Logger.getLogger(TestcaseDAOImpl.class)
                    .error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));

            if (transaction != null)
                transaction.rollback();
        }

        session.close();

        return testcaseCollection;
    }

    @Override
    public void createTestcase(Testcase testcase) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Testcase readTestcase(BigDecimal id) {
        Session session = sessionFactory.openSession();
        Transaction transaction = null;

        Testcase testcase = null;

        try {
            transaction = session.beginTransaction();

            testcase = (Testcase) session.load(Testcase.class, id);

            transaction.commit();
        } catch (final HibernateException ex) {
            Logger.getLogger(TestcaseDAOImpl.class)
                    .error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));

            if (transaction != null)
                transaction.rollback();
        }

        session.close();

        return testcase;
    }

    @Override
    public void updateTestcase(Testcase testcase) {
        Session session = sessionFactory.openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();

            session.update(testcase);

            transaction.commit();
        } catch (final HibernateException ex) {
            Logger.getLogger(TestcaseDAOImpl.class)
                    .error(ex.getMessage() + "\n" + Arrays.toString(ex.getStackTrace()));

            if (transaction != null)
                transaction.rollback();
        }

        session.close();
    }

    @Override
    public void deleteTestcase(BigDecimal testcaseId) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

当更新被称为bamm No Session时。为什么会这样? GetAll成功顺利,但这就是它的全部。在我的日志中,其他所有内容都返回No Session错误。

堆栈跟踪:

14-Nov-2014 16:54:43.012 WARNING [http-apr-8080-exec-148] com.sun.faces.context.SessionMap.put JSF1063: WARNING! Setting non-serializable attribute value into HttpSession (key: testcaseProvider, value class: com.tsystems.tf.beans.TestcaseProvider).
14-Nov-2014 16:54:46.812 WARNING [http-apr-8080-exec-148] com.sun.faces.lifecycle.InvokeApplicationPhase.execute #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
 javax.faces.FacesException: #{testcaseProvider.updateTestcase()}: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 29 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
    at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 30 more

14-Nov-2014 16:54:46.832 SEVERE [http-apr-8080-exec-148] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError javax.faces.el.EvaluationException: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
    at com.tsystems.tf.db.models.Testcase_$$_jvsta1c_0.setTestcaseName(Testcase_$$_jvsta1c_0.java)
    at com.tsystems.tf.beans.TestcaseProvider.updateTestcase(TestcaseProvider.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
    ... 30 more

1 个答案:

答案 0 :(得分:0)

用before()方法替换静态块,并在其末尾添加会话创建:

@Before
public void before() {    
    Configuration configuration = new Configuration();
    configuration = configuration.configure();

    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
    registryBuilder = registryBuilder.applySettings(configuration.getProperties());

    StandardServiceRegistry registry = registryBuilder.build();
    sessionFactory = configuration.buildSessionFactory(registry);
    session = sessionFactory.openSession();
}

和after()方法:

@After
public void after {
    session.close();
    sessionFactory.close();
}

当然,在每次测试中删除所有打开/关闭会话。