NullPointerException while trying to add an orm layer using hibernate

给你一囗甜甜゛ 提交于 2021-02-10 15:14:00

问题


Well,I have been trying to add an orm layer for past 3 weeks and i havent been able to do so.I was trying to learn from the tutorial.I have done whatever the tutorial says .Here is the code

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>

Here the exception

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)

I am a newbie and trying to learn struts hibernate integration.I dont understand why it is trhowing an exception after what i have followed this tutorial http://javatutions.blogspot.com/2013/05/before-we-starts-with-our-first-hello.html

EDIT:what to do if the session is null?


回答1:


Use the @SessionTarget annotation to inject the Hibernate session into the action bean. For this purpose you need the hibernate interceptor to be added to the action config. More about how to use a session and transaction capabilities of the struts2-hiberanate plugin, see in my answer to Struts + Hibernate: @SessionTarget not working. There's also example here, that is well enough to demonstrate the capabilities of the hibernate plugin. The problem that you have is probably related to the package configuration. You don't need to extend struts-default package because it's already extended by the hibernate-default package, or you just have not a hibernate-plugin on the classpath.




回答2:


Answer to your

what to do if the session is null

Normally if you follow the DAO structure, you need to cater for 2 cases before firing any query.

  1. If session exists

    Session hibernateSession = sessionFactory.getCurrentSession();
    
  2. If session is null, we create the session

    Session hibernateSession = sessionFactory.openSession();
    

In case of step 1, you may end up getting a null value if the session is not initialized. And in the case of step 2, you will end up with a new session on every request and you will need to close and handle this session carefully otherwise you may end up with many useless sessions left open in the session pool.

So best practice is to check if getCurrentSession() returns a sessions, otherwise create and return a new session with openSession(). Something like

 Sessions sess = null
 sess = sessionFactory.getCurrentSession();
 if(sess == null){
      sess = sessionFactory.openSession();
 }

Keep in mind that this may not be the most feasible solution in some cases



来源:https://stackoverflow.com/questions/23238455/nullpointerexception-while-trying-to-add-an-orm-layer-using-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!