Struts 2 Hibernate 3 Integration Example Using Annotation

By Arvind Rai, May 11, 2014
In this page we will learn struts 2 and hibernate 3 integration using annotation. I will create a user form and the detail of user will be saved in Mysql database. We will create dao class that will be called from action class. We will understand integration points step by step. To integrate struts 2 with hibernate using full-hibernate-plugin find the link.
Struts 2 + Hibernate 3 Integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget Annotation Example
Now on this page we will integrate struts 2 with hibernate without using full-hibernate-plugin.

Create Table in Mysql

For the demo, we are creating a userdetail table which will consist id, name, email and age of a user.
userdetail Table
CREATE TABLE `userdetail` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(10) NULL DEFAULT NULL,
`email` VARCHAR(10) NULL DEFAULT NULL,
`age` INT(10) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2; 

User Form and Success Page

user.jsp is the user form in which user will fill the information.
user.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2  Hibernate 3 Integration</title>
</head>
<body>
<h1>Struts 2  Hibernate 3 Integration</h1>
<s:form action="result" validate="true" >
	<s:textfield name="name" label="Name"/>
	<s:textfield name="email" label="Email"/>
	<s:textfield name="age" label ="Age"/>
	<s:submit/>
</s:form>
</body>
</html> 
User form page will look like below in which we will fill user information.
Struts 2  Hibernate 3 Integration Example Using Annotation
Find the success page which will appear once the user details is saved in database.
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><head><title>Struts 2  Hibernate 3 Integration</title>
</head>
<body>
<h1>User Detail is saved successfully.</h1>
</body>
</html> 
The page will look like as below.
Struts 2  Hibernate 3 Integration Example Using Annotation

hibernate.cfg.xml and HibernateUtil class

hibernate.cfg.xml has been used for MySQL database configuration.
hibernate.cfg.xml
<hibernate-configuration>
  <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">
    jdbc:mysql://localhost:3306/concretepage</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></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.concretepage.persistence.User"/>
   </session-factory>
</hibernate-configuration> 
To get the hibernate session, we have created below class.
HibernateUtil.java
package com.concretepage;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
	private static final SessionFactory concreteSessionFactory;
	static {
		try {
			concreteSessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}
	public static Session getSession() throws HibernateException {
		return concreteSessionFactory.openSession();
	}
} 

Action, DAO and Entity Class

UserAction class will redirect user form to be displayed.
UserAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/user")
@ResultPath(value="/")
@Result(name="success",location="user.jsp")
public class UserAction extends ActionSupport{
	public String execute() {
	    return SUCCESS;
	}
}
 
ResultAction class has properties and its setter and getter method that will take the data from user input and can provide when needed.
ResultAction.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.concretepage.dao.UserDao;
import com.concretepage.persistence.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
@Namespace("/user")
@ResultPath(value="/")
@Action(value="result", results={@Result(name="success",location="result.jsp")})
public class ResultAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private String name;
	private String email;
	private int age;
	public String execute() {
	   User user = new User(name, email, age);	
	   UserDao userDao = new UserDao();
	   userDao.saveUserDetail(user);
	   return SUCCESS; 
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 
Now find the Entity class for hibernate that maps the user details table.
User.java
package com.concretepage.persistence;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="userdetail")
@Entity
public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	@Id
	@Column(name="id")
	private int id;
	@Column(name="name")
	private String name;
	@Column(name="email")
	private String email;
	@Column(name="age")
	private int age;
	public User(String name, String email,int age){
		this.name = name;
		this.email = email;
		this.age = age;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}  
In UserDao class, we have written a method that will save user detail in database. Hibernate session will be obtained from HibernateUtil.
UserDao.java
package com.concretepage.dao;
import org.hibernate.Session;
import com.concretepage.HibernateUtil;
import com.concretepage.persistence.User;
public class UserDao {
  public void saveUserDetail(User user){
	    Session session = HibernateUtil.getSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		session.close();
		System.out.println("done");
  }
} 
Find the web.xml for struts 2 configuration.
web.xml
<web-app>
  <display-name>Struts 2 Annotation Example</display-name>
   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.concretepage.action</param-value>
        </init-param>
    </filter>
  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app> 

Maven Dependency for Struts 2 and Hibernate 3 Integration

Find the maven dependency for struts 2 and hibernate 3.
pom.xml
<dependencies>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.16</version>
	</dependency>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-convention-plugin</artifactId>
		<version>2.3.8</version>
	</dependency>
    <dependency>
	  <groupId>org.hibernate</groupId>
	  <artifactId>hibernate-annotations</artifactId>
	  <version>3.5.6-Final</version>
    </dependency>
    <dependency>
	  <groupId>org.hibernate.javax.persistence</groupId>
	  <artifactId>hibernate-jpa-2.0-api</artifactId>
	  <version>1.0.1.Final</version>
    </dependency>
    <dependency>
	    <groupId>org.slf4j</groupId>
	    <artifactId>slf4j-api</artifactId>
	    <version>1.7.7</version>
    </dependency>
    <dependency>
	   <groupId>mysql</groupId>
	   <artifactId>mysql-connector-java</artifactId>
	   <version>5.1.17</version>
    </dependency>
  </dependencies> 

Project Structure in Eclipse

All the classes and XML file will look in eclipse as below.
Struts 2  Hibernate 3 Integration Example Using Annotation

Run Application

1. Build the code with the command mvn clean package using command prompt from project root location.
2. Deploy the WAR file in tomcat (I am using tomcat 8).
3. Run the application using the URL
http://localhost:8080/Struts2Demo-1/user/user

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us