Sunday 25 September 2011

Struts2 Hibernate Spring Tutorial

Struts - Hibernate - Spring Application

This is a tutorial that explains how Struts2 , Hibernate and Spring(IoC) is mixed together and used in the same application.

I based my work on the examples given in Vaan Nila Struts2 tutorial. Vaan Nila gives the Struts2Example14 for Struts2 - Spring and Struts2Example17 for Struts2 - Hibernate.

My trick is: I took the Struts2Example17 project and added it the lib/jars of the Struts2Example14. Then I changed the struts.xml from:

/register.jsp

to: (my StrutsHibernateSpring application)

/register.jsp


Similar Struts2Example14 's WEB-INF/applicationContext.xml:





I did WEB-INF/applicationContext.xml in StrutsHibernateSpring:





I also added the Spring listener to the web.xml in StrutsHibernateSpring :

org.springframework.web.context.ContextLoaderListener

which is similar to the Struts2Example14 web.xml.

It worked.

Here is the code:


struts.xml
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">




listUser



/register.jsp





hibernate.config.xml

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">


org.hsqldb.jdbcDriver
jdbc:hsqldb:hsql://localhost
sa

1
org.hibernate.dialect.HSQLDialect
true
create





com.vaannila.dao
UserDAO.java
package com.vaannila.dao;

import java.util.List;
import com.vaannila.domain.User;

public interface UserDAO {

public void saveUser(User user);
public List listUser();
}

UserDAOImpl.java
package com.vaannila.dao;

import java.util.List;

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

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.vaannila.domain.User;

public class UserDAOImpl implements UserDAO {

@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;

@SuppressWarnings("unchecked")
@Override
public List listUser() {
List courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}

@Override
public void saveUser(User user) {
try {
session.save(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}

}

com.vaannila.domain
User.java
package com.vaannila.domain;

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

@Entity
@Table(name="USER")
public class User {

private Long id;
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private Boolean mailingList;

@Id
@GeneratedValue
@Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}

@Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

@Column(name="USER_PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

@Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}

@Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

@Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}

@Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}

}

WebContent
WEB-INF
lib
application-Context.xml







web.xml


StrutsHibernateSpringARS

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter



org.springframework.web.context.ContextLoaderListener


struts2
/*



index.jsp



WebContent
hs.bat
set classpath=.\WEB-INF\lib\hsqldb.jar;%classpath%
java org.hsqldb.Server
hs2.bat
java -cp ./WEB-INF/lib/hsqldb.jar org.hsqldb.util.DatabaseManager




I went one step further and I did a DAO dependency injection in my application StrHibSprARS2.
applicationContext.xml in src together with hibernate.cfg.xml and struts.xml









(It would be wiser to change the name of the applicationContext.xml to beans.xml.)
UserAction.java would change to:
...
//private UserDAO userDAO = new UserDAOImpl();

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
private UserDAO userDAO = (UserDAOImpl) factory.getBean("userDAOImplClass");
...
(again the name applicationContext.xml gets mixed with the real one in the WEB-INF. I tried
successfully to clean up the unnecessary entries in these two applicationContext files, namely
I deleted id="userActionClass" item from the src beans.xml and vise versa. No problem.)

Tuesday 13 September 2011

Some notes about VaanNila's Hibernate Tutorial Examples

This note explains how to run the hibernate examples given
in VaanNila's Hibernate Tutorial.
http://www.vaannila.com/hibernate/hibernate-tutorial/hibernate-tutorial.html

ERRORS MESSAGES AND THE SOLUTIONS:


Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.(HibernateUtil.java:14)


add commons-logging-1.1.1
------------------------------------
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment
INFO: Hibernate 3.2.5
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment
INFO: hibernate.properties not found
12.Eyl.2011 20:08:36 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib

...
INFO: building session factory
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: net/sf/cglib/proxy/CallbackFilter
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.vaannila.util.HibernateUtil.(HibernateUtil.java:14)

cglib problem
add cglib.jar
-------------------------------
12.Eyl.2011 20:10:55 org.hibernate.impl.SessionFactoryImpl
INFO: building session factory
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/objectweb/asm/Type

cglib needs asm.jar
-------------------------------


INFO: exporting generated schema to database
12.Eyl.2011 20:12:25 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: schema export complete
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: insert into COURSES (COURSE_ID, COURSE_NAME) values (null, ?)
Hibernate: call identity()
Hibernate: select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as COURSE2_0_ from COURSES course0_
Physics
Chemistry
Maths
Hibernate: select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?
Hibernate: update COURSES set COURSE_NAME=? where COURSE_ID=?
Hibernate: select course0_.COURSE_ID as COURSE1_0_0_, course0_.COURSE_NAME as COURSE2_0_0_ from COURSES course0_ where course0_.COURSE_ID=?
Hibernate: delete from COURSES where COURSE_ID=?
Hibernate: select course0_.COURSE_ID as COURSE1_0_, course0_.COURSE_NAME as COURSE2_0_ from COURSES course0_
Physics
Mathematics

It works...
-----------
Directory of C:\Users\ars\Desktop\VN_Hibernate\HibernateExample1\lib

antlr-2.7.6.jar
asm.jar
cglib-2.2.jar
commons-collections-3.2.1.jar
commons-logging-1.1.1.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-annotations
hibernate-commons-annotations
hsqldb.jar
javassist-3.4.GA.jar
jta-1.1.jar
slf4j-api-1.6.2.jar
slf4j-simple-1.6.2.jar

Friday 9 September 2011

Some notes about VaanNila's Spring Hibernate Integration Tutorial

Some notes about Vaanilla's Spring Hibernate Integration Tutorial
http://www.vaannila.com/spring/spring-hibernate-integration-1.html

SpringExample17 indicates the below list as necessary dependecies.

01.antlr-2.7.6
02.antlr-runtime-3.0
03.commons-collections-3.1
04.commons-dbcp
05.commons-logging-1.0.4
06.commons-pool
07.dom4j-1.6.1
08.ejb3-persistence
09.hibernate3
10.hibernate-annotations
11.hibernate-commons-annotations
12.hsqldb
13.javassist-3.4.GA
14.jstl
15.jta-1.1
16.org.springframework.asm-3.0.0.M3
17.org.springframework.beans-3.0.0.M3
18.org.springframework.context-3.0.0.M3
19.org.springframework.context.support-3.0.0.M3
20.org.springframework.core-3.0.0.M3
21.org.springframework.expression-3.0.0.M3
22.org.springframework.jdbc-3.0.0.M3
23.org.springframework.orm-3.0.0.M3
24.org.springframework.transaction-3.0.0.M3
25.org.springframework.web-3.0.0.M3
26.org.springframework.web.servlet-3.0.0.M3
27.slf4j-api-1.5.6
28.slf4j-simple-1.5.6
29.standard

I used the below list of dependecies:
Directory of C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent\WEB-INF\lib

antlr-2.7.6.jar
antlr-runtime-3.0.jar
asm.jar
cglib-2.2.jar
commons-collections.jar
commons-dbcp.jar
commons-logging.jar
commons-pool.jar
dom4j-1.6.1.jar
hibernate-annotations.jar
hibernate-commons-annotations.jar
hibernate3.jar
hsqldb.jar
javassist-3.4.GA.jar
javax.persistence.jar
javax.servlet_2.4.0.v200706111738.jar
jstl.jar
jta-1.1.jar
org.springframework.asm-3.1.0.M2.jar
org.springframework.beans-3.1.0.M2.jar
org.springframework.context-3.1.0.M2.jar
org.springframework.context.support-3.1.0.M2.jar
org.springframework.core-3.1.0.M2.jar
org.springframework.expression-3.1.0.M2.jar
org.springframework.jdbc-3.1.0.M2.jar
org.springframework.orm-3.1.0.M2.jar
org.springframework.transaction-3.1.0.M2.jar
org.springframework.web-3.1.0.M2.jar
org.springframework.web.servlet-3.1.0.M2.jar
slf4j-api-1.6.2.jar
slf4j-simple-1.6.2.jar
standard.jar

I had to add asm.jar and cglib-2.2.jar because of the problems listed below.


exception

org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is org.springframework.jdbc.UncategorizedSQLException: Hibernate operation:
Cannot open connection; uncategorized SQLException for SQL [???]; SQL state [null]; error code [0];
Cannot create PoolableConnectionFactory (socket creation error);
nested exception is org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (socket creation error)

root cause

org.springframework.jdbc.UncategorizedSQLException: Hibernate operation:
Cannot open connection; uncategorized SQLException for SQL [???];
SQL state [null]; error code [0];
Cannot create PoolableConnectionFactory (socket creation error);
nested exception is org.apache.commons.dbcp.SQLNestedException:
Cannot create PoolableConnectionFactory (socket creation error)

SOLUTION:
Vaanilla assumes that you know how to run HSQLDB :-)
add hs.bat :
set classpath=.\web-inf\lib\hsqldb.jar;%classpath%
java org.hsqldb.Server

OUTPUT:
C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent>set classpath=.\web-
inf\lib\hsqldb.jar;

C:\Users\ars\Desktop\Str_Hib_Spr\SpringExample17\WebContent>java org.hsqldb.Serv
er
[Server@6ac2a132]: [Thread[main,5,main]]: checkRunning(false) entered
[Server@6ac2a132]: [Thread[main,5,main]]: checkRunning(false) exited
[Server@6ac2a132]: Startup sequence initiated from main() method
[Server@6ac2a132]: Loaded properties from [C:\Users\ars\Desktop\Str_Hib_Spr\Spri
ngExample17\WebContent\server.properties]
[Server@6ac2a132]: Initiating startup sequence...
[Server@6ac2a132]: Server socket opened successfully in 358 ms.
[Server@6ac2a132]: Database [index=0, id=0, db=file:test, alias=] opened sucessf
ully in 156 ms.
[Server@6ac2a132]: Startup sequence completed in 514 ms.
[Server@6ac2a132]: 2011-09-09 20:21:26.494 HSQLDB server 1.8.0 is online
[Server@6ac2a132]: To close normally, connect and execute SHUTDOWN SQL
[Server@6ac2a132]: From command line, use [Ctrl]+[C] to abort abruptly
----------------

exception
...
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
net/sf/cglib/proxy/CallbackFilter
...
SEVERE: Servlet /SpringExample17 threw load() exception
java.lang.ClassNotFoundException: net.sf.cglib.proxy.CallbackFilter

SOLUTION:
add cglib.jar
--------------------

exception

root cause

org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'mySessionFactory' defined in ServletContext resource [/WEB-INF/dispatcher-servlet.xml]:
Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError:
Could not initialize class net.sf.cglib.proxy.Enhancer

SOLUTION:
cglib depends on asm.jar:

add asm.jar
---------------------------


If there are any problems related to antlr add:
antlr-2.7.5H3

If there are still any more problems:
arsaral [at] yahoo [dot] com

Cheers.

Ali R+