Struts 2 + Hibernate Integration with Full-Hibernate-Plugin

By Arvind Rai, March 03, 2016
On this page we will provide struts 2 and hibernate 3 integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget annotation example. Full-Hibernate-Plugin is a third party plugin and not a struts 2 in-built plugin. It makes easy to integrate struts 2 with hibernate. Like spring, we can inject hibernate Session and Transaction in our DAO class using this plugin. Here on this page we will provide a full demo to work with Full-Hibernate-Plugin step by step.

Struts 2 Full-Hibernate-Plugin

To use Struts 2 Full-Hibernate-Plugin, we need to follow below steps.

1. Download struts2-fullhibernatecore-plugin JAR from the URL
https://code.google.com/archive/p/full-hibernate-plugin-for-struts2/downloads
and paste at any location, suppose D:\jar\struts2-fullhibernatecore-plugin-2.2.2-GA.jar in Window OS.

2. Now open the command prompt and run the mvn install as follows (I assume that maven is installed in the system).

mvn install:install-file -Dfile=D:\jar\struts2-fullhibernatecore-plugin-2.2.2-GA.jar -DgroupId=com.google.code -DartifactId=struts2-fullhibernatecore-plugin -Dversion=2.2 -Dpackaging=jar -DgeneratePom=true

3. After successful run of the command, now we can get this JAR using maven in our project as usual.
<dependency>
    <groupId>com.google.code</groupId>
    <artifactId>struts2-fullhibernatecore-plugin</artifactId>
    <version>2.2</version>
</dependency> 

@SessionTarget and @TransactionTarget Annotation

Hibernate Session and Transaction can be injected using Full-Hibernate-Plugin with the below annotations.

@SessionTarget: Instantiate org.hibernate.Session.
@TransactionTarget: Instantiate org.hibernate.Transaction.

Use of @ParentPackage("hibernate-default") and @InterceptorRef("basicStackHibernate")

While integrating struts 2 with hibernate using Full-Hibernate-Plugin, we need to take care three points.

1. @ParentPackage("hibernate-default"): Use hibernate-default as parent package which is provided by Full-Hibernate-Plugin.

2. @InterceptorRef("basicStackHibernate"): The package hibernate-default provides three interceptors.
basicStackHibernate
defaultStackHibernate
defaultStackHibernateStrutsValidation.
For hibernate core Session and Transaction injection capability, we need to use basicStackHibernate interceptor.

3. Use @SessionTarget and @TransactionTarget annotation at class field in DAO class. If DAO is directly being used in Action class, DAO must be instantiated at class level in Action class. If we introduce a Service class to use DAO then DAO must be instantiated at class level in Service class as well as our Service class must also be instantiated at class level in Action class.

If we do not follow these steps, hibernate Session and Transaction will be null.

Project Structure in Eclipse

Find the project structure in eclipse.
Struts 2 + Hibernate 3 Integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget Annotation Example

Database Schema and Entity Class

We are using MySQL database for the demo. Find the table used in example.
Table: user
CREATE TABLE `user` (
	`id` INT(11) NOT NULL,
	`age` INT(11) NULL DEFAULT NULL,
	`email` VARCHAR(255) NULL DEFAULT NULL,
	`name` VARCHAR(255) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 
Find the associated entity.
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="user")
@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(int id, String name, String email,int age){
		this.id = id;
		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;
	}
}  

Maven to Resolve JAR Dependencies

Find the maven file to resolve JAR dependencies.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.concretepage</groupId>
  <artifactId>Struts2Demo</artifactId>
  <packaging>war</packaging>
  <version>1</version>
  <name>Struts2Hibernate</name>
  <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.hibernate</groupId>
	     <artifactId>hibernate-validator</artifactId>
	     <version>4.1.0.Final</version>
	</dependency>
        <dependency>
	     <groupId>org.slf4j</groupId>
	     <artifactId>slf4j-api</artifactId>
	     <version>1.7.7</version>
        </dependency>
	<dependency>
	     <groupId>log4j</groupId>
	     <artifactId>log4j</artifactId>
	     <version>1.2.16</version>
	</dependency>
        <dependency>
	     <groupId>mysql</groupId>
	     <artifactId>mysql-connector-java</artifactId>
	     <version>5.1.17</version>
        </dependency>
        <dependency>
	     <groupId>com.google.code</groupId>
	     <artifactId>struts2-fullhibernatecore-plugin</artifactId>
	     <version>2.2</version>
	</dependency>    
  </dependencies>
</project> 

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> 


Create DAO and Service Class


IUserDAO.java
package com.concretepage.dao;
import com.concretepage.persistence.User;
public interface IUserDAO {
	void saveUserDetail(User user);
} 
UserDao.java
package com.concretepage.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.concretepage.persistence.User;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class UserDao implements IUserDAO {
	@SessionTarget
	private Session session;
	@TransactionTarget
	private Transaction transaction;	
	@Override	
	public void saveUserDetail(User user){
		session.save(user);
		System.out.println("done");
	}
} 
UserService.java
package com.concretepage.service;
import com.concretepage.dao.IUserDAO;
import com.concretepage.dao.UserDao;
import com.concretepage.persistence.User;
public class UserService {
	private IUserDAO userDao = new UserDao();	
	public void saveUserDetail(User user){
		userDao.saveUserDetail(user);
	}
} 
We need to take care that here DAO must be instantiated at class level.

Create Action Class

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.java
package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.concretepage.persistence.User;
import com.concretepage.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
@ParentPackage("hibernate-default")
@Namespace("/user")
@ResultPath(value="/")
@InterceptorRef("basicStackHibernate")
public class ResultAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private String email;
	private int age;
	private UserService service = new UserService();
	@Action(value="save", results={@Result(name="success",location="result.jsp")})	
	public String save() {
	   User user = new User(id, name, email, age);
	   service.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;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
} 
We need to take care that here Service class must be instantiated at class level.

web.xml

<web-app>
  <display-name>Struts 2 Validation Annotation Example</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>
</web-app> 

Create UI

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="save" validate="true" >
	<s:textfield name="id" label="Id"/>
	<s:textfield name="name" label="Name"/>
	<s:textfield name="email" label="Email"/>
	<s:textfield name="age" label ="Age"/>
	<s:submit method="execute"/>
</s:form>
</body>
</html> 
result.jsp
<html>
<head><head><title>Struts 2  Hibernate 3 Integration</title>
</head>
<body>
	<h1>User Detail is saved successfully.</h1>
</body>
</html> 

Output

UI One:
Struts 2 + Hibernate 3 Integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget Annotation Example
UI two:
Struts 2 + Hibernate 3 Integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget Annotation Example
Find the inserted data in database.
Struts 2 + Hibernate 3 Integration with Full-Hibernate-Plugin using @SessionTarget and @TransactionTarget Annotation Example
Find the console output.
done
Hibernate: insert into user (age, email, name, id) values (?, ?, ?, ?) 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us