Struts 2 + Hibernate integration example

In Struts2, there are no official plugins to integrate the Hibernate framework. But, you can workaround with the following steps :

  1. Register a custom ServletContextListener.
  2. In the ServletContextListener class, initialize the Hibernate session and store it into the servlet context.
  3. In action class, get the Hibernate session from the servlet context, and perform the Hibernate task as normal.

See the relationship :


Struts 2 <-- (Servlet Context) ---> Hibernate <-----> Database 

In this tutorial, it shows a simple customer module (add and list function), developed in Struts 2, and perform the database operation with Hibernate. The integration part is using the above stated mechanism (store and retrieve the Hibernate session in the servlet context).

This workaround is very similar with the classic Struts 1.x and Hibernate integration, just the classic Struts 1.x is using the Struts’s plugins; While the Struts 2 is using the generic servlet listener.

1. Project structure

See this full project folder structure.

Struts 2 Hibernate integration example

2. MySQL table script

Create a customer table for the demonstration. Here’s the SQL table script.


DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

3. Dependency

Get the Struts2, Hibernate and MySQL dependency libraries.


//...
	<!-- Struts 2 -->
	<dependency>
	        <groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.1.8</version>
        </dependency>

	<!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

	<!-- Hibernate core -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.7.ga</version>
	</dependency>

	<!-- Hibernate core library dependency start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>

	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>

	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
	<!-- Hibernate core library dependency end -->

	<!-- Hibernate query library dependency start -->
	<dependency>
		<groupId>antlr</groupId>
		<artifactId>antlr</artifactId>
		<version>2.7.7</version>
	</dependency>
	<!-- Hibernate query library dependency end -->
//...

4. Hibernate Stuffs

The Hibernate model and configuration stuffs.

Customer.java – Create a class for customer table.


package com.mkyong.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

	private Long customerId;
	private String name;
	private String address;
	private Date createdDate;

	//getter and setter methods
}

Customer.hbm.xml – Hibernate mapping file for customer.


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
	table="customer" catalog="mkyong">

        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

hibernate.cfg.xml – Hibernate database configuration file.


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">false</property>
    <mapping resource="com/mkyong/customer/hibernate/Customer.hbm.xml" />
  </session-factory>
</hibernate-configuration>

5. Hibernate ServletContextListener

Create a ServletContextListener, and initialize the Hibernate session and store it into the servlet context.

HibernateListener .java


package com.mkyong.listener;

import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateListener implements ServletContextListener{
 
    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;
 
    public static final String KEY_NAME = clazz.getName();

	public void contextDestroyed(ServletContextEvent event) {
	  //
	}
 
	public void contextInitialized(ServletContextEvent event) {
 
	 try { 
	        URL url = HibernateListener.class.getResource(path);
	        config = new Configuration().configure(url);
	        factory = config.buildSessionFactory();
	         
	        //save the Hibernate session factory into serlvet context
	        event.getServletContext().setAttribute(KEY_NAME, factory);
	  } catch (Exception e) {
	         System.out.println(e.getMessage());
	   }
	}
}

Register the listener in the web.xml file.
web.xml


<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</display-name>
  
  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
	  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	</filter-class>
  </filter>
  
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
 
  <listener>
    <listener-class>
	  com.mkyong.listener.HibernateListener
    </listener-class>
  </listener>
 
</web-app>

6. Action

In Action class, get the Hibernate session from the servlet context and perform the Hibernate task as normal.

CustomerAction.java


package com.mkyong.customer.action;

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

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.customer.model.Customer;
import com.mkyong.listener.HibernateListener;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
 
public class CustomerAction extends ActionSupport 
	implements ModelDriven{

	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();
	
	public String execute() throws Exception {
		return SUCCESS;
	}

	public Object getModel() {
		return customer;
	}
	
	public List<Customer> getCustomerList() {
		return customerList;
	}

	public void setCustomerList(List<Customer> customerList) {
		this.customerList = customerList;
	}

	//save customer
	public String addCustomer() throws Exception{
		
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

		Session session = sessionFactory.openSession();

		//save it
		customer.setCreatedDate(new Date());
	 
		session.beginTransaction();
		session.save(customer);
		session.getTransaction().commit();
	 
		//reload the customer list
		customerList = null;
		customerList = session.createQuery("from Customer").list();
		
		return SUCCESS;
	
	}
	
	//list all customers
	public String listCustomer() throws Exception{
		
		//get hibernate session from the servlet context
		SessionFactory sessionFactory = 
	         (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

		Session session = sessionFactory.openSession();

		customerList = session.createQuery("from Customer").list();
		
		return SUCCESS;
	
	}	
}

7. JSP page

JSP page to add and list the customer.

customer.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 + Hibernate integration example</h1>

<h2>Add Customer</h2>
<s:form action="addCustomerAction" >
  <s:textfield name="name" label="Name" value="" />
  <s:textarea name="address" label="Address" value="" cols="50" rows="5" />
  <s:submit />
</s:form>

<h2>All Customers</h2>

<s:if test="customerList.size() > 0">
<table border="1px" cellpadding="8px">
	<tr>
		<th>Customer Id</th>
		<th>Name</th>
		<th>Address</th>
		<th>Created Date</th>
	</tr>
	<s:iterator value="customerList" status="userStatus">
		<tr>
			<td><s:property value="customerId" /></td>
			<td><s:property value="name" /></td>
			<td><s:property value="address" /></td>
			<td><s:date name="createdDate" format="dd/MM/yyyy" /></td>
		</tr>
	</s:iterator>
</table>
</s:if>
<br/>
<br/>

</body>
</html>

8. struts.xml

Link it all ~


<?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>
  <constant name="struts.devMode" value="true" />
 	
  <package name="default" namespace="/" extends="struts-default">
		
    <action name="addCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="addCustomer" >
       <result name="success">pages/customer.jsp</result>
    </action>
	
    <action name="listCustomerAction" 
	class="com.mkyong.customer.action.CustomerAction" method="listCustomer" >
        <result name="success">pages/customer.jsp</result>
    </action>		

  </package>	
</struts>

9. Demo

Access the customer module : http://localhost:8080/Struts2Example/listCustomerAction.action

Struts 2 Hibernate Add Customer

Fill in the name and address fields, hits the submit button, the inserted customer details will be listed immediately.

Struts2 Hibernate List Customer

Reference

  1. Struts 2 + Hibernate integration with “Full Hibernate Plugin”
  2. ServletContextListener documentation
  3. Struts + Hibernate integration example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
44 Comment threads
31 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
48 Comment authors
Yash PatelTad AriqKev YcybergladAnjani Kumar Gupta Recent comment authors
newest oldest most voted
trackback
Struts 2 + Hibernate integration with “Full Hibernate Plugin”

[…] last Struts 2 + Hibernate integration example, it use the servlet context listener to play around with the Hibernate session, and it did […]

trackback
Struts 2 + Spring + Hibernate integration example

[…] Struts 2 + Hibernate integration example […]

tikaa
Guest
tikaa

heii why i can’t insert into database public String insertContacts() throws Exception { try { session.beginTransaction(); session.save(getContacts()); session.getTransaction().commit(); } catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } return SUCCESS; }

Abhishek
Guest
Abhishek

I have two tables in my database.one being “user” where the user email is stored,and the other being “work exp” where the user’s work experience is stored.I am mapping the two tables with an “id”.can you please suggest me the code by which i can map the user id to it’s work experience.
I am using Struts 2 with hibernate and spring.

Thanks in Advance
Abhishek

Ratneswar
Guest
Ratneswar

Hello Yong, I have a configuration issue with weblogic, I am able to see the results in tomcat 6.0.29 without any issues. Issue: struts 2, hibernate, weblogic 9.2 configuration issue Getting data from the database, however, action class not forwarding results to jsp page. In the weblogic logs, action method is continuously running in infinite loop, not sure why behaving it. Here is list method code. public String list() { System.out.println(“entered in to UserAction list() “); SessionFactory sessionFactory = (SessionFactory) ServletActionContext.getServletContext().getAttribute(HibernateListener.KEY_NAME); Session session = sessionFactory.openSession(); userList = userDAO.listUser(); System.out.println(“end UserAction list() ……………”+userList.size()); for (int i = 0; i < userList.size();… Read more »

Oscar Calderon
Guest
Oscar Calderon

Thanks a lot Kong, that post is very useful to me. I work with struts2 but i commit the mistake of initialize an hibernate session factory for each java session (each application user that login) but your approach is more improved. I just have 2 questions (Sorry if my english is strange, i’m from central america): 1. Suppose that i apply your approach in my project and Hibernate session factory is initialized after application is deployed and it works fine, but in some moment, the database is down and connection in the application is lost. Then a user tries to… Read more »

jerson
Guest
jerson

Hi,
I have a dynamic query generating from hibernate and the Result List object cannot be mapped with any of my model calss and now I want to display this list in my jsp page using iterator …How can approach for this..Pls suggest me something

Many Thanks and Regards,
Jerson

padmanabha
Guest
padmanabha

I get following exception when i deploy this example

------------------------------------------------------------------------
SessionFactory sessionFactory = 
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);

ln no.51        Session session = sessionFactory.openSession();
------------------------------------------------------------------------

java.lang.NullPointerException

com.mkyong.customer.action.CustomerAction.addCustomer(CustomerAction.java:51)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
Muthu
Guest
Muthu

This pom is missing with the dependency

javax.servlet
servlet-api
2.5
provided

Muthu
Guest
Muthu

This pom is missing with the dependency

javax.servlet
servlet-api
2.5
provided

ivan mao
Guest
ivan mao

add,

javax.servlet
servlet-api
3.0-alpha-1

and delete,

cglib
cglib
2.2

in pom.xml,it works.

Kev Y
Guest
Kev Y

Maybe adding driver class in hibernate.cfg.xml will solve this problem, and i believe he forgot this.

Justin
Guest
Justin

Thanks for the tutorial.

You create the SessionFactory in the contextInitialized() method of the HibernateListener class. Would it be a good idea to add factory.close() in the contextDestroyed() method? or is this not necessary? Thanks!

subash
Guest
subash

i have imported the downloaded project in Eclipse IDE.
but where i have to place the lib files i am getting confused. will u suggest me

christopher
Guest
christopher

am getting 404 error.Can any one help me out.Thanks in Advance

christopher
Guest
christopher

I have resolved the 404 error.Now am getting error 500

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
	com.mkyong.customer.action.CustomerAction.addCustomer(CustomerAction.java:46)
	sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	java.lang.reflect.Method.invoke(Unknown Source)

note The full stack trace of the root cause is available in the Apache Tomcat/6.0.30 logs.

Kindly help me out.Thanks in Advance

Xin
Guest
Xin

Hi, It is very nice tutorial. I got one issue, I would very appreciate that if you could take a look the following message? >mvn -X compile … [ERROR] Failed to execute goal on project Struts2Example: Could not resolve dependencies for project com.mkyong.common:Struts2Example:war:com.mkyong.common: Failure to find javax.transaction:jta:jar:1.0.1B in http://repo1.maven.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal on project Struts2Example: Could not resolve dependencies for project com.mkyong.common:Struts2Example:war:com.mkyong.common: Failure to find javax.transaction:jta:jar:1.0.1B in http://repo1.maven.org/maven2 was cached in the… Read more »

Xin
Guest
Xin

It couldn’t find jdbc driver. It is ok to me. I am actually using mysql.

Thanks a lot,

Xin

LuZcila
Guest
LuZcila

I have the same problem.
How do you fixed it?

Thanks!

Xin
Guest
Xin

Dear Mkyong,

I got the following error, would you please give a hint?

java.lang.NoClassDefFoundError: javax/transaction/Synchronization
org.hibernate.impl.SessionImpl.(SessionImpl.java:214)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:520)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:544)
org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:552)
com.mkyong.customer.action.CustomerAction.addUser(CustomerAction.java:46)

Thanks in advance,

Xin

Xin
Guest
Xin

One info from mkyong’s site is “This is caused by missing of the β€œjta.jarβ€œ, usually happened in Hibernate transaction development.” But I do have jta-1.0.1B.jar in path.

Xin

Xin
Guest
Xin

Hi Mkyong,

Thank you for reply. It didn’t work even jta-1.0.1B.jar (manually downloaded) was added to path. It finally worked when it was moved to .m2 folder.

Also, it seems that the jar for ServletActionContext is missing. javax.servlet-5.1.12 was downloaded and added to path. is it right version?

I’m also wondering that if you have any comment about this post, here is the url:
http://stackoverflow.com/questions/5687886/storing-hibernate-sessionfactory-with-struts

“I notice the example doesn’t seem to ever close the SessionFactory so I added some code in the contextDestroyed. Was this necessary?”

Thanks for help,

Xin

Java Guru
Guest
Java Guru

Thanks a lot Kong, that post is very good and helpful for me.

santosh limbu
Guest
santosh limbu

i am in love with all your work…..amazing work …

Ali Syed
Guest
Ali Syed

Hi,

Thanks for the tutorial, I believe we need to make the below changes to pom.xml for the example to work on Tomcat 7 and MySQl5.5

Option 1 – Replace cglib 2.2 with cglib-nodep 2.2.2 (contains asm dependencies)

 
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib-nodep</artifactId>
    <version>2.2.2</version>
</dependency>	

Option 2 – Keep cglib 2.2 and add asm dependency

 
<dependency>
	<groupId>cglib</groupId>
	<artifactId>cglib</artifactId>
	<version>2.2</version>
</dependency>
<dependency>
	<groupId>asm</groupId>
	<artifactId>asm</artifactId>
	<version>3.1</version>
</dependency>	
Guillermo
Guest
Guillermo

Thxs!!!!!

Ramon
Guest
Ramon

Thanks, that was the issue with the NullPointerException!

Narasappa
Guest
Narasappa

hi I am Narasappa from bangalore.Currently I am working on Struts 2.0.I need help in displaying image Stored in mysql Using Struts 2.0.please do the the neewd full

tom
Guest
tom

eclipse is giving me this strange missing library requirement.. not surprising as im in linux.

Project ‘Struts2Example’ is missing required library: ‘C:/Program Files/Java/jdk1.6.0_13/lib/tools.jar’

tom
Guest
tom

Why is eclipse in linux show me this?
Project ‘Struts2Example’ is missing required library: ‘C:/Program Files/Java/jdk1.6.0_13/lib/tools.jar’

Anjani Kumar Gupta
Guest
Anjani Kumar Gupta

Need to add tools.jar from jdk in build path

tom
Guest
tom

I’m getting the following error from eclipse
The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files

Does the servlet-api-2.5.jar need to be referenced in the library?

Ryan
Guest
Ryan

any answers on this. im also getting the same eclipse error

Sree Rama Konduri
Guest
Sree Rama Konduri

javax.servlet
servlet-api
2.5

add this to your pom file , that will fix the issue

Krish
Guest
Krish

HI i got this error, I just download this Struts 2 + Hibernate integration example and i placed all dependencies. but i got this error , give me suggestions please to fix this issue SEVERE: Error configuring application listener of class com.mkyong.listener.HibernateListener java.lang.NoClassDefFoundError: Lorg/hibernate/cfg/Configuration; at java.lang.Class.getDeclaredFields0(Native Method) at java.lang.Class.privateGetDeclaredFields(Unknown Source) at java.lang.Class.getDeclaredFields(Unknown Source) at org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(DefaultInstanceManager.java:276) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:143) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:125) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1525) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1515) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.ClassNotFoundException: org.hibernate.cfg.Configuration at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1688) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1533) ... 16 more Mar 13, 2012 3:49:19 PM… Read more »

PhongNQ
Guest
PhongNQ

I got the same errors. May I help you to fix this..
I think it problems in .classpath and tomcat lib but don’t know how to fix it.

tom
Guest
tom

I renamed the classes now I receive this error, but I can’t find where its referenced?

SEVERE: Error configuring application listener of class com.tom.listener.HibernateListener
java.lang.NoClassDefFoundError: com/tom/listener/HibernateListener (wrong name: com/mkyong/listener/HibernateListener)

tom
Guest
tom

The instructions don’t go into any depth on how to create the required ServletContextListener and the referenced link doesnt work

http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html

Can you please out line the steps required in this process – sorry if its so simple it doesnt even need to be explained.

tom
Guest
tom

Mkyong Can you help? If I launch the page directly from http://localhost:8080/Struts2Example/pages/customer.jsp I see the following error in the logs: WARNING: Caught an exception while evaluating expression ‘customerList.size() > 0’ against value stack java.lang.NullPointerException: target is null for method size Upon trying to submit data I receive the following Hibernate error org.hibernate.PropertyValueException: not-null property references a null or transient value: com.paul.customer.model.Customer.createdDate But if i access the project as the example suggests http://localhost:8080/Struts2Example/listCustomerAction.action I see the following struts error report about the Hibernate sql submitted Struts Problem Report Struts has detected an unhandled exception: Messages: Unknown column ‘customer0_.customerId’ in ‘field list’… Read more »

Anshul
Guest
Anshul

hi, I tried to run the example but got the following error: Struts Problem Report Struts has detected an unhandled exception: Messages: File: com/mkyong/customer/action/CustomerAction.java Line number: 71 Stacktraces java.lang.NullPointerException com.mkyong.customer.action.CustomerAction.listCustomer(CustomerAction.java:71) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:662) You are seeing this… Read more »

Janith
Guest
Janith

I had same issue.By changing Hibernate version it worked.
I change pom.xml

org.hibernate
hibernate-entitymanager
4.1.9.Final

Anshul
Guest
Anshul

hi mkyong,

i am getting

Struts has detected an unhandled exception:
Messages:
File: com/mkyong/customer/action/CustomerAction.java
Line number: 71
Stacktraces
java.lang.NullPointerException

line no 71 is SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY_NAME);

It throws null and says

Note: An exception occurred while getting the Javadoc. See log for details.

i can see in the .classpath the values as

which is not there in my system as its an ubuntu system.

Please tell me the remedy for this

Thnaks
Regards
Anshul

Rajesh K
Guest
Rajesh K

hi even i got the same problem..!! let me knw if u solved the issue..!!

File: com/mkyong/customer/action/CustomerAction.java
Line number: 71
Stacktraces
java.lang.NullPointerException

line no 71 is SessionFactory sessionFactory =
(SessionFactory) ServletActionContext.getServletContext()
.getAttribute(HibernateListener.KEY_NAME);

Anshul
Guest
Anshul

hi mkyong,

I did it bymyself πŸ™‚

Thanks

Shaswat
Guest
Shaswat

Hi,
When will listCustomer() method in CustomerAction will be called ????

tom
Guest
tom

How would I go about setting up struts2 xml form validation on the input boxes in this example?