从hibernate检索类会抛出nullpointerexception

时间:2015-09-24 16:12:52

标签: java hibernate

当我通过hibernate从我的数据库中检索一个类时,我遇到了java.lang.NullPointerException。

protected void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    String username = request.getParameter("username");
    String password = request.getParameter("password");

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session1 = sessionFactory.openSession();
    session1.beginTransaction();

    User user = (User)session1.get(User.class, username); 

    System.out.println(user.getUsername());
    System.out.println(user.getPassword());

    if (user.getPassword().equals(password)) {

        request.setAttribute("user", user);

        request.setAttribute("loggedIn", "true");

        session1.getTransaction().commit();
        session1.close();
        sessionFactory.close();

        request.getRequestDispatcher("/WEB-INF/jsp/view/mainPage.jsp").forward(request, response);

    } else {

        session1.getTransaction().commit();
        session1.close();
        sessionFactory.close();

        request.setAttribute("loggedIn", "false");

        request.getRequestDispatcher("/WEB-INF/jsp/view/startPage.jsp").forward(request, response);
    }
}

这是我的servlet中处理登录的方法。 (不确定我是否使用sessionFactory最佳)。从session.get(Class,arg)

之后的两行
System.out.println(user.getUsername());
System.out.println(user.getPassword());

我得到了正确的值,所以我说我成功检索了对象,当我将//添加到

//request.setAttribute("user", user);

工作正常。当我发出requestDispatcher时,也会抛出这种情况。

我假设它与我的用户拥有的ArrayList有关。这是用户。

@Entity
public class User {

@GeneratedValue(strategy=GenerationType.AUTO) 
private long empId;
@Id
private String username;
private String firstname;
private String lastname;
private String organisation;
private String password;
private String email;

@OneToMany
private Collection<Marker> bookmarks = new ArrayList<>();

public User() {

}

public User(String username, String password, String email) {
    this.username = username;
    this.password = password;
    this.email = email;
}

public Collection<Marker> getBookmarks() {
    return bookmarks;
}

public void setBookmarks(Collection<Marker> bookmarks) {
    this.bookmarks = bookmarks;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.username = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.username = email;
}

public long getEmpId() {
    return empId;
}

public void setEmpId(long empId) {
    this.empId = empId;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public String getLastname() {
    return lastname;
}

public void setLastname(String lastname) {
    this.lastname = lastname;
}

public String getOrganisation() {
    return organisation;
}

public void setOrganisation(String organisation) {
    this.organisation = organisation;
}

@Override
public String toString()
{
    return this.username;
}

}

这是控制台日志:

java.lang.NullPointerException
    at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:273)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:200)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:541)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
    at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:348)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:224)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:155)
    at javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
    at org.apache.jsp.WEB_002dINF.jsp.view.mainPage_jsp._jspx_meth_c_005fforEach_005f0(mainPage_jsp.java:354)
    at org.apache.jsp.WEB_002dINF.jsp.view.mainPage_jsp._jspService(mainPage_jsp.java:313)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:431)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
    at com.Tooblo.eventHandler.login(eventHandler.java:195)
    at com.Tooblo.eventHandler.doGet(eventHandler.java:61)
    at com.Tooblo.eventHandler.doPost(eventHandler.java:212)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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:502)
    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:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

sep. 24, 2015 6:08:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [eventHandler] in context with path [/Toobloo] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.hibernate.collection.internal.AbstractPersistentCollection.openTemporarySessionForLoading(AbstractPersistentCollection.java:273)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:200)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:541)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132)
    at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:277)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:348)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:224)
    at org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:155)
    at javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:256)
    at org.apache.jsp.WEB_002dINF.jsp.view.mainPage_jsp._jspx_meth_c_005fforEach_005f0(mainPage_jsp.java:354)
    at org.apache.jsp.WEB_002dINF.jsp.view.mainPage_jsp._jspService(mainPage_jsp.java:313)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:431)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
    at com.Tooblo.eventHandler.login(eventHandler.java:195)
    at com.Tooblo.eventHandler.doGet(eventHandler.java:61)
    at com.Tooblo.eventHandler.doPost(eventHandler.java:212)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    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:502)
    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:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

在我更改数据库连接之前,它似乎有效,但是新的是在我的另一台计算机上。

2 个答案:

答案 0 :(得分:2)

尝试@OneToMany(fetch = FetchType.EAGER)。它主要在加载主实体时加载关系。它总是可能不是一个好方法。这链接:Difference between FetchType LAZY and EAGER in Java Persistence API?&amp; when to use Lazy loading / Eager loading in hibernate?会给你一个更好的主意。

答案 1 :(得分:1)

一些事情。

  1. 您需要将数据库逻辑与servlet类分开。创建一个新的服务/ DAO层并从您的servlet调用您的服务。

  2. 创建sessionFactory时需要小心。每次创建新的sessionFactory时,都将打开与DB的新连接。你不希望这样。为sessionFactory实现单例模式并共享它。

  3. 确保在进行每次休眠呼叫后正确打开和关闭session