Home Struts Struts Struts2.2.1 Hibernate4 Struts Integration

Ask Questions?

View Latest Questions


 
 

Hibernate4 Struts Integration
Posted on: March 28, 2012 at 12:00 AM
Advertisement
In this tutorial you will learn how to Integrate Hibernate 4 with Struts2

Stuts2 Hibernate4 Integration

You can also access the database using Hibernate in Struts2. Following is the project structure :-

Write the following query to make table in the database 'data'

CREATE TABLE `registration` (
  `id` int(11) NOT NULL auto_increment,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) default NULL,
  `phone_no` decimal(16,0) default NULL,
  `email` varchar(150) default NULL,
  `address` text,
  `gender` varchar(5) default NULL,
  PRIMARY KEY  (`id`)
)

Write the following domain class and map the table as

Registration.java

package net.roseindia.domain;

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

@Entity
@Table(name = "registration")
public class Registration {

	@Id
	@GeneratedValue
	@Column(name = "id")
	private Integer id;

	@Column(name = "first_name")
	private String firstName;

	@Column(name = "last_name")
	private String lastName;

	@Column(name = "phone_no")
	private Long phoneNo;

	@Column(name = "email")
	private String email;

	@Column(name = "address")
	private String address;

	@Column(name = "gender")
	private String gender;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Long getPhoneNo() {
		return phoneNo;
	}

	public void setPhoneNo(Long phoneNo) {
		this.phoneNo = phoneNo;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

Map the Registration class in the hibernate.cfg.xml as

hibernate.cfg.xml

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

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/data
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</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.current_session_context_class">thread</property>

<mapping class="net.roseindia.domain.Registration" />
</session-factory>
</hibernate-configuration>

Write the Connection class as

ConnectionUtil.java

package net.roseindia.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class ConnectionUtil {
	private static ServiceRegistry serviceRegistry;
	private static SessionFactory sessionFactory;
	static {
		try {
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Make a Service inteface as

Service.java

package net.roseindia.service;

import net.roseindia.domain.Registration;

public interface Service {
	public void saveData(Registration registration);
}

Make A ServiceImpl class

ServiceImpl.java

package net.roseindia.service.serviceImpl;

import net.roseindia.domain.Registration;
import net.roseindia.service.Service;
import net.roseindia.util.ConnectionUtil;

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

public class ServiceImpl implements Service {

	public void saveData(Registration registration) {
		Session session = null;
		try {
			ConnectionUtil connectionFactory = new ConnectionUtil();
			session = connectionFactory.getSessionFactory().openSession();
			Transaction transaction = session.beginTransaction();
			session.save(registration);
			transaction.commit();
			session.flush();
			session.close();
		} catch (Exception e) {
			e.getMessage();
			e.printStackTrace();
		}
	}

}

Write the two JSP files one for form and another for diplaying data

registration.jsp

<%@taglib prefix="s" uri="/struts-tags"%>
<h2 align="center">Registration Form</h2>
<center><s:form action="doRegistation" method="POST">
	<s:textfield name="firstName" size="50" label="First Name"></s:textfield>
	<s:textfield name="lastName" size="50" label="Last Name"></s:textfield>
	<s:textfield name="phoneNo" size="50" label="Phone Number"></s:textfield>
	<s:textfield name="email" size="50" label="Email Address"></s:textfield>
	<s:textarea name="address" cols="38" label="Address"></s:textarea>
	<s:radio list="genderList" name="gender" label="Gender"></s:radio>
	<s:submit value="Register"></s:submit>
</s:form></center>

home-page.jsp

<h2 align="center">The Following Record Has Been Added</h2>
<center>
<table cellpadding="5" cellspacing="5" bgcolor="#EBFFD6">
<tr>
<td>First Name</td>
<td>:</td>
<td>${firstName}</td>
</tr>
<tr>
<td>Last Name</td>
<td>:</td>
<td>${lastName}</td>
</tr>
<tr>
<td>Phone Number</td>
<td>:</td>
<td>${phoneNo}</td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td>${email}</td>
</tr>
<tr>
<td>Address</td>
<td>:</td>
<td>${address}</td>
</tr>
<tr>
<td>Gender</td>
<td>:</td>
<td>${gender}</td>
</tr>
<tr>
<td colspan="3" align="center">
<button onclick="JavaScript: window.print();">Print</button>
</td>
</tr>
</table>
</center>

Write the Action class as

RegistrationAction.java

package net.roseindia.action;

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

import net.roseindia.domain.Registration;
import net.roseindia.service.Service;
import net.roseindia.service.serviceImpl.ServiceImpl;

import com.opensymphony.xwork2.ActionSupport;

public class RegistrationAction extends ActionSupport {
	
	private List genderList = new ArrayList();
	private String firstName;
	private String lastName;
	private Long phoneNo;
	private String email;
	private String address;
	private String gender;

	private Service service;

	public RegistrationAction() {
		genderList.add("Male");
		genderList.add("Female");
		service = new ServiceImpl();
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public Long getPhoneNo() {
		return phoneNo;
	}

	public void setPhoneNo(Long phoneNo) {
		this.phoneNo = phoneNo;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public List getGenderList() {
		return genderList;
	}

	public void setGenderList(List genderList) {
		this.genderList = genderList;
	}

	public String execute() throws Exception {

		Registration registration = new Registration();
		registration.setFirstName(firstName);
		registration.setLastName(lastName);
		registration.setAddress(address);
		registration.setEmail(email);
		registration.setGender(gender);
		registration.setPhoneNo(phoneNo);

		service.saveData(registration);
		return SUCCESS;
	}
}

And Finally map the Action in struts.xml file as

stuts.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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />

<package name="roseindia" extends="struts-default">

<action name="register" class="net.roseindia.action.RegistrationAction">
<result name="success">/jsp/registration.jsp</result>
</action>

<!-- Redirect to another namespace -->

<action name="doRegistation" class="net.roseindia.action.RegistrationAction">
<result name="success">/jsp/home-page.jsp</result>
<result name="input">/jsp/registration.jsp</result>
</action>

</package>

</struts>


When you run this application it will display message as shown below:


 

Download Select Source Code

Related Tags for Hibernate4 Struts Integration:


DMCA.com