尝试使用hibernate添加orm层时出现NullPointerException

时间:2014-04-23 08:08:40

标签: java hibernate configuration struts2 struts2-s2hibernate

好吧,我一直试图在过去3周内添加一个orm层,但我还是没能这样做。我正在尝试从教程中学习。我已经完成了教程所说的任何内容。这是代码

Student.java

package com.codinghazard.actions;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student {

   @Id
   @GeneratedValue
   private int id;
   @Column(name="last_name")
   private String lastName;
   @Column(name="first_name")
   private String firstName;
   private int marks;
   public int getId() {
    return id;
   }
   public void setId(int id) {
    this.id = id;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public int getMarks() {
      return marks;
   }
   public void setMarks(int marks) {
      this.marks = marks;
   }
}

StudentDAO.java

package com.codinghazard.actions;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.googlecode.s2hibernate.struts2.plugin.
                     annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.
                     annotations.TransactionTarget;

public class StudentDAO {

   @SessionTarget
   Session session;

   @TransactionTarget
   Transaction transaction;

   @SuppressWarnings("unchecked")
   public List<Student> getStudents()
   {
      List<Student> students = new ArrayList<Student>();
      try
      {
         students = session.createQuery("from Student").list();
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
      return students;
   }

   public void addStudent(Student student)
   {
       try
       {           
           session.save(student);
       }
       catch(Exception e)
       {
           System.out.println("Exception is "+e);
       }
   }
}

AddStudentAction.java

package com.codinghazard.actions;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.codinghazard.actions.Student;
import com.codinghazard.actions.StudentDAO;

@SuppressWarnings("serial")
public class AddStudentAction extends ActionSupport 
            implements ModelDriven<Student>{

   Student student  = new Student();
   List<Student> students = new ArrayList<Student>();
   StudentDAO dao = new StudentDAO();
   public Student getModel() {
      return student;
   }

   public String execute()
   {
      dao.addStudent(student);
      return "success";
   }

   public String listStudents()
   {
      students = dao.getStudents();
      return "success";
   }

   public Student getStudent() {
      return student;
   }

   public void setStudent(Student student) {
      this.student = student;
   }

   public List<Student> getStudents() {
      return students;
   }

   public void setStudents(List<Student> students) {
      this.students = students;
   }

}

的hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory name="java:hibernate/SessionFactory">
   <property name="hibernate.connection.driver_class">c
      om.mysql.jdbc.Driver
   </property>
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/driverregistration
   </property>
   <property name="hibernate.connection.username">root</property>
   <property name="hibernate.connection.password">admin</property>
   <property name="hibernate.connection.pool_size">10</property>
   <property name="show_sql">true</property>
   <property name="dialect">
      org.hibernate.dialect.MySQLDialect    
   </property>
   <property name="hibernate.hbm2ddl.auto">update</property>
   <mapping class="com.codinghazard.actions.Student" />
</session-factory>
</hibernate-configuration> 

struts.xml中

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <!-- http://localhost:8080/test/user/login -->

   <constant name="struts.devMode" value="true" />


    <package name="user" namespace="/user" extends="struts-default,hibernate-default">





      <action name="addStudent" method="execute"
         class="com.codinghazard.actions.AddStudentAction">
         <result name="success" type="redirect">
               listStudents
         </result>
      </action>

      <action name="listStudents" method="listStudents"
         class="com.codinghazard.actions.AddStudentAction">
         <result name="success">pages/student.jsp</result>
      </action>

        <action name="userinput">
            <result>pages/input.jsp</result>
        </action>

        <action name="userinputaction" class="com.codinghazard.actions.CustomerAction"
        method="execute">
         <result name="success" type="chain" >fetchDriver</result>
      </action>

      <action name="fetchDriver" class="com.codinghazard.actions.customerEmailAction"
        method="getDriver">
         <result name="success" type="chain" >customeremail</result>
      </action>


      <action name="customeremail" 
      class="com.codinghazard.actions.customerEmailAction"
      method="call">
        <result>pages/emailsuccess.jsp</result>
        <result name="error">pages/error.jsp</result>
      </action>

        <action name="login">
            <result>pages/login.jsp</result>
        </action>

        <action name="loginaction" class="com.codinghazard.actions.LoginAction" >
         <result name="success">pages/userExists.jsp</result>
         <result name="error">pages/notExists.jsp</result>
      </action>

        <action name="Calculator">
            <result>pages/Calculator.jsp</result>
        </action>

        <action name="email">
            <result>pages/email.jsp</result>
        </action>

        <action name="uploader">
            <result>pages/upload.jsp</result>
        </action>

        <action name="emailer" 
         class="com.codinghazard.actions.Emailer"
         method="execute">
         <result name="success">pages/emailsuccess.jsp</result>
         <result name="error">pages/error.jsp</result>
      </action>

        <action name="upload" class="com.codinghazard.actions.uploadFile">
      <interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload"/>
            <param name="allowedTypes">text/plain</param>
            <param name="maximumSize">10240</param>
        <interceptor-ref name="defaultStack">  
        </interceptor-ref>     
       <result name="success">pages/success.jsp</result>
       <result name="error">pages/error.jsp</result>
   </action>

        <action name="Welcome" class="com.codinghazard.actions.WelcomeAction">
        <interceptor-ref name="timer" />
        <interceptor-ref name="defaultStack"/>
            <result name="SUCCESS">pages/Result.jsp</result>
            <result name="ERROR">pages/error.jsp</result>

        </action>



    </package>

</struts>

这里有例外

java.lang.NullPointerException
    at com.codinghazard.actions.StudentDAO.getStudents(StudentDAO.java:28)
    at com.codinghazard.actions.AddStudentAction.listStudents(AddStudentAction.java:30)
    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:601)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:292)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:255)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:211)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:190)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:90)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:192)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:187)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:510)
    at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

我是一个新手并且正在尝试学习struts hibernate集成。我不明白为什么在我按照本教程http://javatutions.blogspot.com/2013/05/before-we-starts-with-our-first-hello.html

之后它会出现异常

编辑:如果会话为空,该怎么办?

2 个答案:

答案 0 :(得分:1)

使用@SessionTarget注释将Hibernate会话注入操作bean。为此,您需要将hibernate拦截器添加到操作配置中。有关如何使用struts2-hiberanate插件的会话和事务功能的更多信息,请参阅我对Struts + Hibernate: @SessionTarget not working的回答。还有示例here,这足以证明hibernate插件的功能。您遇到的问题可能与package configuration有关。您不需要扩展struts-default包,因为它已经由hibernate-default包扩展,或者您只是在类路径上没有hibernate-plugin。

答案 1 :(得分:0)

回答你的

  

如果会话为空,该怎么办

通常,如果您遵循DAO结构,则需要在触发任何查询之前满足2个案例。

  1. 如果会话存在

    Session hibernateSession = sessionFactory.getCurrentSession();
    
  2. 如果session为null,我们创建会话

    Session hibernateSession = sessionFactory.openSession();
    
  3. 如果是步骤1,如果未初始化会话,您最终可能会获得空值。在步骤2的情况下,您将在每个请求上结束新的会话,并且您需要小心地关闭并处理此会话,否则您最终可能会在会话池中打开许多无用的会话。

    因此,最佳做法是检查getCurrentSession()是否返回会话,否则创建并返回openSession()的新会话。像

    这样的东西
     Sessions sess = null
     sess = sessionFactory.getCurrentSession();
     if(sess == null){
          sess = sessionFactory.openSession();
     }
    

    请记住,在某些情况下,这可能不是最可行的解决方案