Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Tuesday, 2 July 2013

Struts 2-Hibernate 3 integration(complete) using eclipse

hi

i am going to give you complete example of struts 2.0.11 and hibernate 3 integration

well let me start from eclipse configuration,i am using eclipse 3.3 for development,it is nice and stable

step1- create Dynamic web project in eclipse .

step2- now i am going to give configuration of struts 2.0.11 in project open web.xml

and add struts filter for applying struts 2 ,write this in web.xml in
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Another thing you have to do is to put (create) struts.xml file in src folder of eclipse

and put required library for struts (common-logging.jar,freemarker.jar,ognl.jar,struts2-

core.jar, xwork.jar)

This is basic configuration for struts 2

Step-3 now it is time to configure hibernate with struts for that we required hibernate and its required

Libraries in web-Inf/lib folder, complete list:

antlr.jar, asm.jar, cglib.jar, commons-beanutils.jar, common-logging.jar, dom4j.jar

freemarker.jar, hibernate.jar, jta.jar, <jdbc drivers libs>, ognl.jar, struts2.jar, xwork.jar

Step4-we have to create session factory of hibernate in struts 2 filter, so we will extend struts 2 filter,

Create class in src folder for create plugin of hibernate

In your own package structure, I have create HibernateUtil.java in org.hns.plugin

HibernateUtil.java
package org.hns.plugin;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;

public class HibernateUtil {
private static SessionFactory sessionFactory;
public static void createSessionFactory() {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static Session getSession() {
return sessionFactory.openSession();
}
}
Struts2dispatcher.java
package org.hns.plugin;

import javax.servlet.*;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.hibernate.HibernateException;

public class Struts2Dispatcher extends FilterDispatcher {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
try {
HibernateUtil.createSessionFactory();
System.out.print("application initializing successfully");
} catch (HibernateException e) {
throw new ServletException(e);
}
}
}

Step-5
package org.hns.plugin;

import javax.servlet.*;
import org.apache.struts2.dispatcher.FilterDispatcher;
import org.hibernate.HibernateException;

public class Struts2Dispatcher extends FilterDispatcher {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
try {
HibernateUtil.createSessionFactory();
System.out.print("application initializing successfully");
} catch (HibernateException e) {
throw new ServletException(e);
}
}
}
Step-6 - apply this filter in web.xml like
<!--<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> -->
<filter-class>org.hns.plugin.Struts2Dispatcher</filter-class>

Step-7 we have to put hibernate configuration file in src folder with the name 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>
<property>true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/user</property>
<property>usr</property>
<property>usr</property>

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property>org.hibernate.transaction.JDBCTransactionFactory</property>
</session-factory>
</hibernate-configuration>
Give your connection url, username, password, jdbc driver class name, for this example I have used mysql database

I have used user schema with usr  username and password, in user schema there is usermast table with the field usercode(int),uname(varchar),pwd(varchar),type(varchar), you can create table and put 2-3 dummy entry in your wishing database.

Step-8

It is time to create hibernate mapping with table and mapping class

I have create User.java in org.hns.user package
package org.hns.user.;
public class User
{
private int id;
private String username;
private String password;
private String usertype;
// add fields setter and getter here (required)
}
Create User.hbm.xml in org.hns.user (org/hns/user/ OR where User.java created) like
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="usermast">
<id column="usercode">
<generator></generator>
</id>

<property name="username" column="uname" />
<property column="pwd" />
<property column="type" />
</class>
</hibernate-mapping>
You can get more idea about any another advance mapping stuff from any hibernate tutorial.

Here property is java class variable name and column is table column name.

Step-9 add this mapping to hibernate.cfg.xml using
<mapping resource="org/hns/user/User.hbm.xml"/>
Step-10 the basic settings for using hibernate for usermast table has been completed here.

Step-11

now I am create another java file UserHibDao.java in  org.hns.user.dao  for create and access user dao
package org.hns.user.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hns.user.User;
import org.sm.plugin.HibernateUtil;

public class UserHibDao {

private List<User> userlist;
private User user;

public void delete(Integer id) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
user=(User)session.get(User.class,id);
session.delete(user);
tx.commit();

}catch (RuntimeException e) {
if(tx != null) tx.rollback();
throw e;
} finally {
session.close();
}
}

public List getAllUser() {
Session session = HibernateUtil.getSession();
try
{
session.beginTransaction();
userlist=session.createQuery("from User").list();
return userlist;

}
catch(Exception e)
{
System.out.print("Error while fetching "+e);
return null;
}
finally
{
session.close();
}

}

public User getuser(Integer id) {
Session session = HibernateUtil.getSession();
try {
session.beginTransaction();
//change query for get proper data
Query q = session.createQuery("from User u where u.uid=:id");
q.setInteger("userid",id);
return (User) q.uniqueResult();
}finally {
session.close();
}
}
public void insert(User usr) {
Session session = HibernateUtil.getSession();
Transaction tx=null;
try {
tx = session.beginTransaction();
session.save(usr);
tx.commit();
} catch (RuntimeException e) {
if(tx != null) tx.rollback();
throw e;
} finally {
session.close();
}
}

public void update(User usr) {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx=session.beginTransaction();
session.update(usr);
tx.commit();
}catch (RuntimeException e) {
if(tx != null) tx.rollback();
throw e;
} finally {
session.close();
}

}
}
So after this stuff you can either use this class for creating service layer of dao or you can use this class functions directly for set business logic.
here one thing should be noted that hibernate query fire on its class object not directly on table so i have used

somthing like this session.createQuery("from User u where u.uid=:id"); instead of using session.createQuery("from usermast u where u.uid=:id");[tablename query]

hope this is enough to start with struts 2 and hibernate 3 ,if you feel still there is some stuff missing in this blog ,let me know from comment

Thanks :-)))

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...