Notes on Spring and Hibernate

Q# How do you implement transaction handling in spring and hibernate?

This looks like a very good explanation of spring and hibernate transaction handling:
http://java.dzone.com/articles/spring-hibernate-persistence
It first discusses hibernate the traditional way, using session etc.then describes hibernate using spring templates.
With Spring, you do not need to implement code for obtaining Session objects, starting and committing transactions, and handling Hibernate exceptions. Instead, you use a HibernateTemplate instance to delegate persistence calls to Hibernate, without direct interaction with Hibernate.
This page would clear any questions about spring/hibernate including transaction handling, etc.
Also
http://static.springsource.org/spring/docs/2.0.8/reference/transaction.html
Spring declarative transaction types
@Transactional
Enum Constants
Enum Constant and Description
MANDATORY
Support a current transaction, throw an exception if none exists.
NESTED
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
Support a current transaction, create a new one if none exists.
REQUIRES_NEW
Create a new transaction, and suspend the current transaction if one exists.
SUPPORTS
Support a current transaction, execute non-transactionally if none exists.

JDBC is a Java standard for database connection. JPA isolates the Java developer from the inner workings of JDBC and database operations. Hibernate, EclipseLink, OpenJPA and Data Nucleus are famous JPA implementations. JTA is a standard for transactions, allowing for management of multiple transactions among multiple databases. JPA utilizes JDBC for database connections and SQL-related operations, and -optionally- utilizes JTA for delegating distributed transaction management details to it.

Q# How does hibernate implement caching programatically?

There are two types of caching – first-level and second-level. First-level cache is hibernate’s internal cache that it uses for optimizing. Second-level caching, is what we normally refer to as caching generally. Secondary level caching is usually implemented using an algorithm like Least Recently Used algorithm.
From
http://www.informit.com/articles/article.aspx?p=353736&seqNum=5
By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
From
http://cuppajavamattiz.com/2010/07/30/hibernate-ehcache-and-caching/
First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.
To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.

Implementing caching programatically
We specify which classes to cache and the caching params but we don’t really write code to invoke the cache.
http://www.informit.com/articles/article.aspx?p=353736&seqNum=5 #Configuring a Cache.
If you feel certain that the problems are due to the amount of traffic between your application and the database. The solution in this case may be a cache. By storing the data in a cache instead of relying solely on the database, you may be able to significantly reduce the load on the database, and possibly to increase overall performance as well.
Regardless of which cache you choose, you will need to tell Hibernate what sort of cache rules should be applied to your data. This is defined using the cache tag. You can place the cache tag in your *.hbm.xml files or in the hibernate.cfg.xml file. Alternatively, you can configure cache settings programmatically using the Configuration object.

Q# How do you configure hibernate using spring?

Hibernate Integration with Spring http://java.dzone.com/articles/spring-hibernate-persistence
http://elope.wordpress.com/2007/09/06/difference-between-jpa-and-hibernate/
When the application uses hibernate using hibernate.cfg.xml, the Session Factory configured through it is available to the DAO class.

SessionFactory sessionFactory =new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = sesssion.beginTransaction();
Object obj = session.get(....);
session.createQuery("HQL_query");
tx.commit();
session.close();

Spring’s Hibernate Support
The datasource is configured in Spring’s application context xml. The datasource might be configured using a JNDI context as well. Spring provides support for hibernate through the HibernateDaoSupport class. The HibernateDao support wraps the HibernateTemplate which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. The session factory is passed a reference to the configured datasource in the spring context. The hibernate template is an abstraction around the usual boilerplate code written when only hibernate is used; and takes care of managing transactions, handling exceptions, managing connections and delegating persistence calls to hibernate. save(), load(), get(), which is invoked on the hibernate session, can be invoked on the hibernate template as well, in addition to find() and findByCriteria() not exposed by the hibernate session.
Spring’s IOC layer also allows the DAO class to be loosely coupled from the service layer and be configured through xml files. In a spring application, the dao layer is usually separated from the business layer by a service facade pattern. Transaction management can be done decoratively instead of code.
When you use JPA with Spring the underlying Hibernate or EJB3 implementation of the persistence layer is hidden and JPA act as a wrapper over them.

The DAO class(Spring) is a wrapper over HibernateTemplate(Spring) which in turn wraps the Hibernate session object which in turn wraps the Hibernate Session Factory. Obtain session from sessionfactory, open transaction from session, commit/ rollback the transaction and close the session. Get hibernateTemplate(Spring) from SessionFactory(Hibernate) to perform the perisistence operations. Don’t work directly with session in Spring. Spring obtains instances of Session objects from the SessionFactory instance. Exceptions emerging from Hibernate are handled by the Spring layer and transactions can be managed if required declaratively by the Spring layer.

Q# Explain lazy loading and eager fetch in hibernate.

If object A has relation with object B, if you load object A, object B is not loaded from db automatically; it will be loaded only when you do getB(). Eager fetch is the opposite technique. In eager fetch B is loaded when A is loaded if A contains B. The default mechanism is lazy loading.
When to use lazy loading and when to use eager fetch:
Lazy load will not automatically load child objects. It will load child objects only when getChild() is called. Eager fetch will automatically load child objects when the parent object is loaded.
Whether to use lazy load or eager fetch depends on your performance requirements.
If you use eager fetch children were already loaded and are already in memory so accessing these objects will be faster. Memory consumption will be more because more objects are in memory even if they are not needed.If you use lazy load, child objects are loaded only when required (when getter method is invoked). Hence accessing child objects will be somewhat slower but will use lesser memory since objects are loaded only if they are required.
http://powerdream5.wordpress.com/2007/11/09/eager-loading-in-hibernate/

Q# Give some advantages of JPA over hibernate. When do we use hibernate and when do we use JPA?

JPA is a wrapper around ORM technology such as EJB3 and Hibernate among others.
Hibernate 3.0 as well as EJB3 implement and support JPA. Code written using JPA uses a standard Java API so that it is generic and implementation agnostic. I could switch hibernate to use something else like iBatis etc. Beneath JPA, the underlying persistence mechanism could be hibernate or toplink or jbatis etc. JPA delegates the database transactions to the underlying persistence layer. The underlying persistence mechanism could be changed anytime and the JPA code wouldn’t change.

And hibernate 3.0 implements the JPA specification so TopLink and other O/R mapping framework.So your code depends upon JPA Api and its implementation is supplied by any JPA impl vendor framework. So in effect if you use JPA , you are using a standard Java Api and not some orthogonal Api and hence you have flexibility in your system. Say initially you have used Hibernate but now want to shift to Other framework.That means JPA supports pluggable persistence providers. JPA specification is heavily influenced by current O/R mapping frameworks like Hibernate and Top-Link.

Q# What is cascade-all in Hibernate? What are its advantages?

In a hibernate mapping file, if you specify cascade=”none” means that saving or deleting first hibernate object has no affect on related object. cascade=”save” means if first object is saved it automatically saves the related object. Similarly cascade delete will delete related object. cascade=”all” is everything save, delete etc even if they are related with foreign keys. The FK constraints etc. everything gets deleted and hibernate takes care of that.
eg.
The code to add a Child looks like this

Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
p.addChild(c);
session.save(c);
session.flush()

You can address the frustrations of the explicit call to save() by using cascades.

Cascade in hibernate (saving child objects as well) and cascade in sql(deleting rows in parent table when fk related child tables rows are deleted)

Q# What is dirty checking in hibernate? What are its advantages?

Dirty checking is hibernate is an internal mechanism that ensures that the value of the hibernate POJO object matches what is in the database(synchronizes). If the value does not match it is said to be “dirty” and hence value is refreshed from the database. Hibernate updates only “dirty” objects – only objects that have changed. Hibernate keeps track of which objects are dirty and occasionally “flushes” to ensure the objects are in sync with the db. The advantages of dirty checking is if hibernate doesn’t keep track of which objects are dirty it would have to update all objects that were loaded even if they didn’t change at the final commit of the transaction.

What are bean scopes in Spring?

1. singleton(default*)
Scopes a single bean definition to a single object instance per Spring IoC container.
2. prototype
Scopes a single bean definition to any number of object instances.
3. request
Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
4. session
Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
5. global session
Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Difference between a Java singleton and a Spring singleton

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.
In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.
In summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.

Protected: Short Note On Spring Boot

This content is password protected. To view it please enter your password below:

Migrating to a standalone Spring Hibernate application

Look here for updated version http://cuppajavamattiz.com/2013/01/16/polishing-the-standalone-spring-hibernate-example/

An interesting experiment. I am trying to run a proof-of-concept standalone spring-hibernate application. I modified the jsf-spring-hibernate web application to run as a standalone: http://cuppajavamattiz.com/2007/09/15/a-simple-spring-hibernate-example/ It proved challenging but jsf backing beans not being strongly tied to the request-response mechanism helped and there was minimum possible modification.

I have used Eclipse for the following project.

Add the following jars to the classpath section of your eclipse project:

All jars from spring-framework-2.5.4-with-dependencies.zip under the following folders:
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\dist
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\dist\modules
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\hibernate
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\log4j
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\jakarta-commons – minus commons-attributes-compiler.jar
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\dom4j
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\ehcache
spring-framework-2.5.4-with-dependencies\spring-framework-2.5.4\lib\c3p0

An extra download would be for jta.jar.

And of course you would have to add the mysql driver to the classpath. I am using
mysql-connector-java-5.0.8-bin.jar.

MySql database is the same as used in the previous example.

The configuration file for spring-hibernate is mattiz.xml placed in >resources< folder under root.

mattiz.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 
<beans>
    <bean id="mattiz.hibernate.dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/AUTHORS" />
        <property name="user" value="admin" />
        <property name="password" value="admin" />
    </bean>
    <bean id="mattiz.abstract.hibernate.sessionfactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"
        abstract="true" lazy-init="true">
        <property name="dataSource">
            <ref local="mattiz.hibernate.dataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>
    <bean id="mattiz.pageSize" class="java.lang.Integer">
        <constructor-arg value="5000"></constructor-arg>
    </bean>
    <bean id="mattiz.hibernate.sessionfactory" parent="mattiz.abstract.hibernate.sessionfactory">
        <property name="mappingResources">
            <list>
                <value>resources/Authors.hbm.xml</value>
            </list>
        </property>
    </bean>
    <bean id="mattiz.transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="mattiz.hibernate.sessionfactory" />
        </property>
    </bean>
    <bean id="mattiz.hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory">
            <ref bean="mattiz.hibernate.sessionfactory" />
        </property>
    </bean>
    <bean id="mattiz.mattizDAO" class="com.mattiz.persistence.data.AuthorLookupBean"
        singleton="true">
        <property name="hibernateTemplate">
            <ref bean="mattiz.hibernateTemplate" />
        </property>
    </bean>
    <bean id="mattiz.client" class="com.mattiz.web.managedbeans.AuthorSearchCreateBean"
        singleton="true">
        <property name="serviceManager" ref="mattiz.service.manager" />
    </bean>
    <bean id="mattiz.service.manager" class="com.mattiz.service.spring.DefaultServiceManager"
        singleton="true">
        <property name="authorLookup" ref="mattiz.mattizDAO" />
    </bean>
</beans>

Note
Though this is a standalone app, in a spring web application you can have mattiz.xml file instead of applicationcontext.xml as the spring configuration file. ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a context-param element named “contextConfigLocation.” Example:

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mattiz.xml</param-value>
        </context-param>
    </listener-class>
</listener>

To define hibernate mapping file in a spring web app add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext file in the web/WEB-INF directory or in mattiz.xml as in the standalone example above.

<property name="mappingResources">
    <list>
        <value>resources/Authors.hbm.xml</value>
    </list>
</property>
</bean>

resources folder under root also contains the mapping hibernate file:

Authors.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
    <class name="com.mattiz.persistence.beans.Authors" table="AUTHORS"
        lazy="false">
        <id name="isbn_Code" type="java.lang.String" column="ISBN_CODE"
            length="10" />
        <property name="author" type="java.lang.String" column="AUTHOR"
            length="50" />
    </class>
</hibernate-mapping>

The classes from the jsf spring hibernate example have been reused with minor changes:

Client Side code:

AuthorSearchCreateBean.java

package com.mattiz.web.managedbeans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mattiz.service.spring.AuthorsBean;
import com.mattiz.service.spring.DefaultServiceManager;
import com.mattiz.service.spring.ServiceManager;

public class AuthorSearchCreateBean {
	private ApplicationContext applicationContext;
	private String isbnCode;
	private String author;
	private AuthorsBean authorsBean;
	private ServiceManager serviceManager;

	public ServiceManager getServiceManager() {
		serviceManager = (DefaultServiceManager) applicationContext
				.getBean("mattiz.service.manager");
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbnCode() {
		return isbnCode;
	}

	public void setIsbnCode(String isbnCode) {
		this.isbnCode = isbnCode;
	}

	public String addAuthor() {
		serviceManager = getServiceManager();
		serviceManager.addAuthor(isbnCode, author);
		return "two";
	}

	public String findAuthor() {
		serviceManager = getServiceManager();
		authorsBean = serviceManager.findAuthor(isbnCode);
		isbnCode = authorsBean.getIsbnCode();
		author = authorsBean.getAuthor();
		return author;
	}

	public AuthorsBean getAuthorsBean() {
		return authorsBean;
	}

	public void setAuthorsBean(AuthorsBean authorsBean) {
		this.authorsBean = authorsBean;
	}

	public static void main(String[] args) {
        AuthorSearchCreateBean authorSearchCreateBean = new AuthorSearchCreateBean();
        authorSearchCreateBean.applicationContext = new ClassPathXmlApplicationContext(
                "resources/mattiz.xml");
        authorSearchCreateBean.isbnCode = "007";
        authorSearchCreateBean.author = "Bond";
        authorSearchCreateBean.addAuthor();
        authorSearchCreateBean.isbnCode = "007";
        String authorFromDB = authorSearchCreateBean.findAuthor();
        System.out.println("AUTHOR IS " + authorFromDB);
    }
}

Note
While Bean Factory is used for simple applications, the Application Context is spring’s more advanced container. Like ‘BeanFactory’ it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide
1) a means for resolving text messages, including support for internationalization.
2) a generic way to load file resources.
3) events to beans that are registered as listeners.

Because of additional functionality, ‘Application Context’ is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, ‘BeanFactory’ is used. One of the commonly used implementation of ‘Application Context’ is the ClassPathXmlApplicationContext. It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code:

AuthorSearchCreateBean authorSearchCreateBean = new AuthorSearchCreateBean();
authorSearchCreateBean.applicationContext = new ClassPathXmlApplicationContext("resources/mattiz.xml");
....
serviceManager = (DefaultServiceManager) applicationContext.getBean("mattiz.service.manager");

Service layer classes:

DefaultServiceManager.java

package com.mattiz.service.spring;

import com.mattiz.persistence.data.AuthorLookupBean;
import com.mattiz.service.spring.AuthorsBean;

public class DefaultServiceManager implements ServiceManager {
	private AuthorLookupBean authorLookup;

	public void addAuthor(String isbnCode, String author) {
		authorLookup.insertAuthor(isbnCode, author);
	}

	public AuthorsBean findAuthor(String isbnCode) {
		AuthorsBean authorsBean = authorLookup.lookupIsbn(isbnCode);
		return authorsBean;
	}

	public AuthorLookupBean getAuthorLookup() {
		return authorLookup;
	}

	public void setAuthorLookup(AuthorLookupBean authorsLookup) {
		this.authorLookup = authorsLookup;
	}
}

ServiceManager.java

package com.mattiz.service.spring;
public interface ServiceManager {
public void addAuthor(String isbnCode, String author);
public AuthorsBean findAuthor(String isbnCode);
}

Value Object Class:

AuthorsBean.java

package com.mattiz.service.spring;

public class AuthorsBean {
	String author;
	String isbnCode;

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbnCode() {
		return isbnCode;
	}

	public void setIsbnCode(String isbnCode) {
		this.isbnCode = isbnCode;
	}
}

The DAO class:

AuthorLookupBean.java

package com.mattiz.persistence.data;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.mattiz.persistence.beans.Authors;
import com.mattiz.service.spring.AuthorsBean;

public class AuthorLookupBean {
	private HibernateTemplate hibernateTemplate;

	public AuthorsBean lookupIsbn(String isbn) throws DataAccessException {
		// List l = getHibernateTemplate().find(
		// "from Authors author where author.isbnCode = ?", isbn);//use when
		// isbn is not PK
		Authors author = null;
		author = (Authors) getHibernateTemplate().load(Authors.class, isbn);
		AuthorsBean authorsBean = new AuthorsBean();
		authorsBean.setAuthor(author.getAuthor());
		authorsBean.setIsbnCode(author.getIsbn_Code());
		return authorsBean;
	}

	public void insertAuthor(String isbn, String authorName)
			throws DataAccessException {
		Authors authors = new Authors();
		authors.setAuthor(authorName);
		authors.setIsbn_Code(isbn);
		HibernateTemplate template = getHibernateTemplate();
		template.saveOrUpdate(authors);
		System.out.println("Inserted/Updated Author, ISBN " + authorName + " "
				+ isbn);
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
}

The interface for the DAO:

IAuthorLookupBean

package com.mattiz.persistence.data;

import org.springframework.dao.DataAccessException;
import com.mattiz.service.spring.AuthorsBean;

public interface IAuthorLookupBean {
	public AuthorsBean lookupIsbn(String isbn) throws DataAccessException;

	public void insertAuthor(String isbn, String authorName);
}

The Domain object:

Authors.java

package com.mattiz.persistence.beans;

public class Authors {
	String author;
	String isbn_Code;

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbn_Code() {
		return isbn_Code;
	}

	public void setIsbn_Code(String isbn_Code) {
		this.isbn_Code = isbn_Code;
	}
}

Run AuthorSearchCreateBean.java as a standalone.
The output would be something like this:


Inserted/Updated Author, ISBN Bond 007
AUTHOR IS Bond

I have used a main method in AuthorSearchCreateBean.java to insert/update and retrieve data from the existing database. There is much to be desired. A GUI interface for entering data and displaying data could be developed. You could try a hand at a Swing based data entry/display mechanism to enhance the P-O-C. Good luck!

A Simple Spring-Hibernate Example

The notes on the simple session bean and entity bean examples on this blog use EJB1.1. Sadly, now it seems that the latest versions of JBoss no longer support this version of EJB. So you would not be able to run the Entity Bean and Session Bean examples posted earlier on this blog with the latest versions of JBoss.
Also there seems to be an increasing trend to use ORM (Object Relational Model) persistence frameworks such as Hibernate.
I describe below a simple hibernate example. I am using jboss-4.2.1.GA and spring-framework-2.0.6-with-dependencies.zip as the integrated Spring-Hibernate package.
The version of Ant I am using is 1.7.0

I am using the same database used with the earlier examples. For convenience I am repeating the scripts you need to run after a fresh mySQL installation:

--user=root mysql
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' IDENTIFIED BY 'admin' WITH GRANT OPTION;
create database AUTHORS;
use AUTHORS;
CREATE TABLE authors (ISBN_CODE varchar(10) NOT NULL default '0',AUTHOR varchar(30) default NULL,PRIMARY KEY  (ISBN_CODE)) ;
insert into authors (ISBN_CODE,AUTHOR )values("1e","matty");

The username and password for mySQL is assumed to be “admin” and “admin”.

The mySQL datasource is configured in spring-servlet.xml and hence mysql-ds.xml is not required to be deployed in server/default/deploy:

Copy mysql-connector-java-3.1.8-bin.jar mySQL driver to jboss’s lib folder

Add the following to log4j.xml to server/default/conf folder


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
	debug="false">

	<!-- ================================= -->
	<!-- Preserve messages in a local file -->
	<!-- ================================= -->

	<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
		<param name="File" value="${jboss.server.home.dir}/log/mattiz.log" />
		<param name="Append" value="true" />
		<param name="MaxFileSize" value="100MB" />
		<param name="MaxBackupIndex" value="3" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d %-5p [%c] %m%n" />
		</layout>
	</appender>

	<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<param name="Threshold" value="INFO" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] %m%n" />
		</layout>
	</appender>

	<category name="javax.faces">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>

	<category name="org.jboss.axis">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>

	<category name="org.jboss.management">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>

	<category name="org.apache">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>

	<category name="org.hibernate">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>
	<category name="org.springframework">
		<priority value="ERROR" />
		<appender-ref ref="FILE" />
	</category>
	<category name="org.jboss">
		<priority value="INFO" />
		<appender-ref ref="FILE" />
	</category>
	<category name="com.mattiz">
		<priority value="DEBUG" />
	</category>
	<root>
		<appender-ref ref="CONSOLE" />
		<appender-ref ref="FILE" />
	</root>
	<!--error -> warn -> info -> debug -->
</log4j:configuration>

My work folder for Ant looks like this:
simple_spring
Web layer configuration files:

web.xml looks like this:


<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

	<!-- Spring listener -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
</listener-class>
	</listener>

	<!-- Faces Servlet -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Faces Servlet Mapping -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/spring-servlet.xml /WEB-INF/applicationContext*.xml
</param-value>
	</context-param>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Note
It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

faces-config.xml looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
	<application>
		<variable-resolver>
			org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
		<locale-config>
			<default-locale>en</default-locale>
			<supported-locale>de</supported-locale>
			<supported-locale>fr</supported-locale>
		</locale-config>
	</application>
	<!-- Managed Beans -->
	<managed-bean>
		<managed-bean-name>authorSearchCreate</managed-bean-name>
		<managed-bean-class>
			com.mattiz.web.managedbeans.AuthorSearchCreateBean
</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>serviceManager</property-name>
			<value>#{serviceManager}</value>
		</managed-property>
	</managed-bean>
	<!-- Managed Beans End -->
	<!-- Navigation Rules -->
	<navigation-rule>
		<from-view-id>/mattizpages/authors.jsp</from-view-id>
		<navigation-case>
			<from-outcome>one</from-outcome>
			<to-view-id>/mattizpages/pageOne.jsp</to-view-id>
			<redirect />
		</navigation-case>
		<navigation-case>
			<from-outcome>two</from-outcome>
			<to-view-id>/mattizpages/pageTwo.jsp</to-view-id>
			<redirect />
		</navigation-case>
	</navigation-rule>
</faces-config>

Spring configuration files

applicationContext.xml looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
	<bean id="authorLookup" class="com.mattiz.persistence.data.AuthorLookupBean">
		<property name="hibernateTemplate">
			<ref bean="hibernateTemplate" />
		</property>
	</bean>
	<bean id="serviceManager" class="com.mattiz.service.spring.DefaultServiceManager">
		<property name="authorLookup">
			<ref bean="authorLookup" />
		</property>
	</bean>
</beans>


Note:

There are two types of dependency injection: setter injection and constructor injection.

Setter Injection: Normally in all the java beans, we use setter and getter method to set and get the value of property as follows:


public class DefaultServiceManager implements ServiceManager {
....
public AuthorLookupBean getAuthorLookup() {
return authorLookup;
}
public void setAuthorLookup(AuthorLookupBean authorsLookup) {
this.authorLookup = authorsLookup;
}
}

We create an instance of the bean ‘DefaultServiceManager’ (say serviceManager) and set property as

 serviceManager.setAuthorLookup(authorLookup);

in spring configuration file as follows. To set properties that reference other beans, the “ref” subelement of “property” is used.


<bean id="serviceManager" class="com.mattiz.service.spring.DefaultServiceManager">
<property name="authorLookup">
<ref bean="authorLookup" />
</property>
</bean>
...
<bean id="authorLookup" class="com.mattiz.persistence.data.AuthorLookupBean">
...
</bean>

Constructor injection;: For constructor injection, we use constructor with parameters as shown below:


public class namebean {
	String name;

	public namebean(String a) {
		name = a;
	}
}

We set the property ‘name’ while creating an instance of the bean ‘namebean’ as namebean bean1 = new namebean(“tom”);

Here we use the constructor-arg element to set the the property by constructor injection as


<bean id="bean1" class="namebean">
	<constructor-arg>
		<value>My Bean Value</value>
	</constructor-arg>
</bean>

OR here


<bean id="mattiz.pageSize" class="java.lang.Integer">
	<constructor-arg value="5000"></constructor-arg>
</bean>

spring-servlet.xml looks like this:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!-- - Application context definition for "springapp" DispatcherServlet. -->
<beans>
	<!-- Business Layer beans definition -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
	</bean>
	<!-- MySQL DataSource Definition -->
	<bean id="dataSourceMySQL" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/AUTHORS" />
		<property name="username" value="admin" />
		<property name="password" value="admin" />
	</bean>
	<!-- Hibernate SessionFactory Definition -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="mappingJarLocations">
			<value>WEB-INF/lib/mattiz.jar</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">
					org.hibernate.dialect.MySQLDialect
				</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
		<property name="dataSource">
			<ref local="dataSourceMySQL" />
		</property>
	</bean>
	<!-- Hibernate Template Defintion -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory">
			<ref local="sessionFactory" />
		</property>
		<property name="cacheQueries" value="false" />
		<property name="jdbcExceptionTranslator">
			<ref local="jdbcExceptionTranslator" />
		</property>
	</bean>
	<bean id="jdbcExceptionTranslator"
		class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
		<property name="dataSource">
			<ref local="dataSourceMySQL" />
		</property>
	</bean>
</beans>

Note
You configure your database driver in spring using datasource “org.springframework.jdbc.datasource.DriverManagerDataSource”. In this example we use org.apache.commons.dbcp.BasicDataSource


<bean id="dataSourceMySQL" class="org.apache.commons.dbcp.BasicDataSource"
	destroy-method="close">
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/AUTHORS" />
	<property name="username" value="admin" />
	<property name="password" value="admin" />
</bean>

You can configure JNDI instead of datasource in spring configuration file using “org.springframework.jndi.JndiObjectFactoryBean”. Example here:


<bean id="dataSourceMySQL" class="org.springframework.jndi.JndiObjectFactoryBean">
	<property name="jndiName" value="java:/dbpool" />
</bean>

build.xml looks like this:


<?xml version="1.0"?>
<project name="mattiz" default="deploy" basedir=".">
	<!-- Grab the environment variables we need -->
	<property environment="env" />
	<property name="DEPLOY_LOC" value="${env.JBOSS_HOME}/server/default/deploy" />
	<!-- Base Properties -->
	<property name="src" value="src/server" />
	<property name="build_root" value="build" />
	<property name="build_dir" value="build/mattiz" />
	<property name="conf_dir" value="conf" />
	<property name="lib_dir" value="lib/third-party" />
	<property name="web.dir" value="src/webpages" />
	<property name="output.filename" value="${ant.project.name}.war" />
	<property name="classes_dest" value="build/mattiz/WEB-INF/classes" />
	<property name="output.project.jar" value="${ant.project.name}.jar" />
	<!-- classpath containing ALL jars (for building) -->
	<path id="build_classpath">
		<pathelement path="${classpath}" />
		<fileset dir="${lib_dir}">
			<include name="**/*.jar" />
		</fileset>
		<pathelement location="${classes_dest}" />
	</path>
	<!-- target: clean -->
	<target name="clean" description="--> clean build">
		<!-- kill the contents of build -->
		<delete failonerror="false" includeemptydirs="true">
			<fileset dir="${build_root}" includes="**/*" />
		</delete>
	</target>
	<!-- target: undeploy -->
	<target name="undeploy" description="--> removes war from app server">
		<delete file="${DEPLOY_LOC}/${output.filename}" />
		<delete dir="${DEPLOY_LOC}/${output.filename}" />
	</target>
	<!-- target: deploy -->
	<target name="deploy" depends="clean, package" description="--> deploys war to app server">
		<copy file="${build_root}/${output.filename}" tofile="${DEPLOY_LOC}/${output.filename}"
			overwrite="true" />
	</target>
	<!-- target: package Construct a war in the build dir -->
	<target name="package" depends="build">
		<copy todir="${build_dir}">
			<fileset dir="${web.dir}" />
		</copy>
		<!-- copy the deploy libs to lib -->
		<copy overwrite="true" todir="${build_dir}/WEB-INF/lib">
			<fileset dir="${lib_dir}" />
		</copy>
		<!-- copy the xmls to WEB-INF -->
		<copy overwrite="true" todir="${build_dir}/WEB-INF">
			<fileset dir="${conf_dir}/jbossWebRoot/WEB-INF" />
		</copy>
		<!-- copy the Hibernate mapping files to the classes tree -->
		<copy overwrite="true" todir="${classes_dest}">
			<fileset dir="src/server" excludes="**/*.java" />
		</copy>
		<!-- copy the spring files to META-INF -->
		<copy overwrite="true" todir="${build_dir}/WEB-INF">
			<fileset dir="${conf_dir}/spring" includes="*" />
		</copy>
		<!-- jar up the classes (and any config files in the class tree) -->
		<jar destfile="${build_dir}/WEB-INF/lib/${output.project.jar}"
			basedir="${build_dir}/WEB-INF/classes" includes="**/*.class,**/*.xml"
			excludes="*.txt" />
		<!-- delete the classes directory (because it's already in the jar in WEB-INF/lib -->
		<delete dir="${build_dir}/WEB-INF/classes" />
		<!-- make the war -->
		<jar destfile="${build_root}/${output.filename}" basedir="${build_dir}"
			includes="**" excludes="**/.*" />
	</target>
	<!-- target: build Build class files to the build dir (not to the src dir) -->
	<target name="build" description="builds project src">
		<mkdir dir="${classes_dest}" />
		<javac srcdir="src" destdir="${classes_dest}" classpathref="build_classpath"
			debug="yes" source="1.5" />
	</target>
</project>

Authors.java


package com.mattiz.persistence.beans;

public class Authors {
	String author;
	String isbn_Code;

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbn_Code() {
		return isbn_Code;
	}

	public void setIsbn_Code(String isbn_Code) {
		this.isbn_Code = isbn_Code;
	}
}

Authors.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>
	<class name="com.mattiz.persistence.beans.Authors" table="AUTHORS"
		lazy="false">
		<id name="isbn_Code" type="java.lang.String" column="ISBN_CODE"
			length="10" />
		<property name="author" type="java.lang.String" column="AUTHOR"
			length="50" />
	</class>
</hibernate-mapping>

AuthorLookupBean.java


package com.mattiz.persistence.data;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.mattiz.persistence.beans.Authors;
import com.mattiz.service.spring.AuthorsBean;

public class AuthorLookupBean extends HibernateDaoSupport {

	public AuthorsBean lookupIsbn(String isbn) throws DataAccessException {
		// List l = getHibernateTemplate().find(
		// "from Authors author where author.isbnCode = ?", isbn);//use when
		// isbn is not PK
		Authors author = null;
		author = (Authors) getHibernateTemplate().load(Authors.class, isbn);
		AuthorsBean authorsBean = new AuthorsBean();
		authorsBean.setAuthor(author.getAuthor());
		authorsBean.setIsbnCode(author.getIsbn_Code());
		return authorsBean;
	}

	public void insertAuthor(String isbn, String authorName)
			throws DataAccessException {
		Authors authors = new Authors();
		authors.setAuthor(authorName);
		authors.setIsbn_Code(isbn);
		getHibernateTemplate().saveOrUpdate(authors);
	}
}

Note
Hibernate provides the load() method and a get method:
author = (Authors) getHibernateTemplate().load(Authors.class, isbn);
OR
author = (Authors)session.load(Authors.class, isbn);
If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null.

Note on Hibernate DAO support
Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.

Note on Hibernate Session

Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

// Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context.
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes.

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:


Session session = null;
Authors author = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (Authors)session.load(Authors.class, isbn);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}

AuthorsBean.java


package com.mattiz.service.spring;

public class AuthorsBean {
	String author;
	String isbnCode;

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbnCode() {
		return isbnCode;
	}

	public void setIsbnCode(String isbnCode) {
		this.isbnCode = isbnCode;
	}
}

DefaultServiceManager.java


package com.mattiz.service.spring;

import com.mattiz.persistence.data.AuthorLookupBean;
import com.mattiz.service.spring.AuthorsBean;

public class DefaultServiceManager implements ServiceManager {
	private AuthorLookupBean authorLookup;

	public void addAuthor(String isbnCode, String author) {
		authorLookup.insertAuthor(isbnCode, author);
	}

	public AuthorsBean findAuthor(String isbnCode) {
		AuthorsBean authorsBean = authorLookup.lookupIsbn(isbnCode);
		return authorsBean;
	}

	public AuthorLookupBean getAuthorLookup() {
		return authorLookup;
	}

	public void setAuthorLookup(AuthorLookupBean authorsLookup) {
		this.authorLookup = authorsLookup;
	}
}

ServiceManager.java


package com.mattiz.service.spring;

public interface ServiceManager {
	public void addAuthor(String isbnCode, String author);

	public AuthorsBean findAuthor(String isbnCode);
}

AuthorSearchCreateBean.java


package com.mattiz.web.managedbeans;

import com.mattiz.persistence.data.AuthorLookupBean;
import com.mattiz.service.spring.AuthorsBean;
import com.mattiz.service.spring.ServiceManager;

public class AuthorSearchCreateBean {
	private String isbnCode;
	private String author;
	private AuthorsBean authorsBean;
	private ServiceManager serviceManager;
	private AuthorLookupBean authorLookup;

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getIsbnCode() {
		return isbnCode;
	}

	public void setIsbnCode(String isbnCode) {
		this.isbnCode = isbnCode;
	}

	public String addAuthor() {
		serviceManager.addAuthor(isbnCode, author);
		System.out.println("Return from AuthorsSearchCreateBean:: add Author");
		return "two";
	}

	public String findAuthor() {
		authorsBean = serviceManager.findAuthor(isbnCode);
		isbnCode = authorsBean.getIsbnCode();
		author = authorsBean.getAuthor();
		System.out.println("Return from AuthorsSearchCreateBean:: find Author");
		return "one";
	}

	public AuthorLookupBean getAuthorLookup() {
		return authorLookup;
	}

	public void setAuthorLookup(AuthorLookupBean authorLookup) {
		this.authorLookup = authorLookup;
	}
}

I have used the following jars from the spring-framework-2.0.6-with-dependencies.zip package
All jars under:
spring-framework-2.0.6-with-dependencies/dist
spring-framework-2.0.6-with-dependencies/dist/modules
spring-framework-2.0.6-with-dependencies/lib/hibernate
spring-framework-2.0.6-with-dependencies/lib/log4j
spring-framework-2.0.6-with-dependencies/lib/jakarta-commons – minus commons-attributes-compiler.jar

Place these in lib/third-party.

authors.jsp


<%@page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib
uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
	<body>
		<f:view>
			<h:form id="authorForm">
				<p>
					<br />
					<h:outputText value="Enter ISBN code" />
					<h:inputText value="#{authorSearchCreate.isbnCode}"
						maxlength="6" size='6' />
					<br />

					<h:outputText value="Enter name of author" />
					<h:inputText value="#{authorSearchCreate.author}"
						maxlength="6" size='6' />
					<br />
					<h:commandButton id="addAuthorId"
						action="#{authorSearchCreate.addAuthor}" value="ADD" type="submit" />
					<h:commandButton id="findAuthorId"
						action="#{authorSearchCreate.findAuthor}" value="FIND" type="submit" />
				</p>
			</h:form>
		</f:view>
	</body>
</html>

pageOne.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@
taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib
uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
	<body>
		<f:view>
			AUTHOR FOUND:
			<br />
				ISBN :
				<h:outputText value="#{authorSearchCreate.isbnCode}" />
				<br />
				AUTHOR :
				<h:outputText value="#{authorSearchCreate.author}" />
				<br />
		</f:view>
	</body>
</html>

pageTwo.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@
taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib
uri="http://java.sun.com/jsf/core" prefix="f"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<body>
		<f:view>
			AUTHOR ADDED WITH ISBN
		</f:view>
	</body>
</html>

index.jsp


<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
	<head></head>
	<body>
		<jsp:forward page="/mattizpages/authors.jsf" />
	</body>
</html>

The war file has the following structure:

<mattiz.war>
    index.jsp
    <meta-INF>
    <mattizpages>
        authors.jsp
        pageOne.jsp
        pageTwo.jsp
    <web-INF>
        applicationContext.xml
        faces-config.xml
        spring-servlet.xml
        web.xml
        spring.tld
        <lib>
           {jars mentioned above AND mattiz.jar}
        <<mattiz.jar>>
            <meta-INF>
            <com>
               <mattiz>
                  <persistence>
                      <beans>
                          Authors.java
                          Authors.hbm.xml
                      <data>
                          AuthorLookupBean.java
                  <service>
                      <spring>
                          AuthorsBean.java
                          DefaultServiceManager.java
                          ServiceManager.java
                  <web>
                      <managedbeans>
                          AuthorSearchCreateBean.java

To run the application perform the following steps:
1.set JBOSS_HOME and ANT_HOME environment variables to appropriate folders containing the

<bin>

folder in ant and jboss. Also set

<ant>/<bin>

in your path variable.
2. construct work folder as described above
3.Open dos prompt at work folder to build project – “ant deploy”
To redeploy – “ant undeploy” – and then – “ant deploy”
When you run build.bat at the dos prompt, the files in

<src>

folder are compiled and appropriate class files are placed in folder, jar and war files are created and the war file is deployed to

<server>/<default>

folder.
Start jboss:

Type the following url on the browser:

http://localhost:8080/mattiz/index.jsp

Download source code here Simple_Spring_Hibernate_Example

A short note on Spring

Spring is a framework for J2EE. It has a number of layers including a MVC web layer, an AOP layer, DAO layer. One can leverage Spring’s DAO Support since Spring has a number of helper classes for JDBC and Hibernate that makes handling connections and Hibernate sessions easy.
Spring uses an Inversion Of Control (IoC) design which basically allows one to connect objects through descriptor configuration files instead of instantiating them through code. One creates an interface for both the service layer and the DAO layer. You can then create concrete implementations of these interfaces.
In the Spring configuration file one defines what concrete DAO class should be set on the service class. The concrete service object is also retrieved by making a call to the Spring “container”.
When the service object is instantiated, the container also instantiates the DAO object and sets it on the service object. What’s nice about this is that should the service class or DAO class ever change we need make changes only in the descriptor configuration files and not in the classes.
If the initial implementation of the DAO class was using Hibernate and for some reason we had to later use straight JDBC, then you create a new DAO object and change the Spring configuration without modifying the service layer at all.
Dependency lookup:
This is the EJB approach.
Dependency Injection:
Here the application objects are not responsible for looking up resources they depend upon. Instead IoC container configures the object externalizing resource lookup from application code. That is dependencies are injected into objects. The lookups are completely removed from application objects.

More useful information from this http://www.mydeveloperconnection.com/html/spring-hibernate-QnA.htm :

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:

1. The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code.

More about the Bean Factory:
Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is “org.springframework.beans.factory.xml.XmlBeanFactory” It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory.

BeanFactory  factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));

This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn’t instantiate the bean yet. To retrieve a bean from a ‘BeanFactory’, the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean’s properties using dependency injection.

myBean bean1 = (myBean)factory.getBean("myBean");

Application Context:
While Bean Factory is used for simple applications, the Application Context is spring’s more advanced container. Like ‘BeanFactory’ it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide
1) a means for resolving text messages, including support for internationalization.
2) a generic way to load file resources.
3) events to beans that are registered as listeners.

Because of additional functionality, ‘Application Context’ is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, ‘BeanFactory’ is used. The three commonly used implementation of ‘Application Context’ are :

i. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code

ApplicationContext    context = new ClassPathXmlApplicationContext("bean.xml");

An example is shown in the standalone class AuthorSearchCreateBean.java http://cuppajavamattiz.com/2008/06/14/migrating-to-a-standalone-spring-hibernate-application/ .

authorSearchCreateBean.applicationContext = new org.springframework.context.support.ClassPathXmlApplicationContext("resources/mattiz.xml");
.....
serviceManager = (DefaultServiceManager) applicationContext.getBean("mattiz.service.manager");

ii. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code

ApplicationContext    context = new FileSystemXmlApplicationContext("bean.xml");

iii. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

2. Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.

3. Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module p
rovides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
More on AOP
Aspect-oriented programming, or AOP is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn’t need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features.

4. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

5. Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including Hibernate SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies.

6. Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts and JSF.

7. Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP.

Advantages of Spring

a. Spring has layed architecture. Use what you need and leave you don’t need now.
b. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continous integration and testability.
c. Dependency Injection and Inversion of Control Simplifies JDBC
d. Open source and no vendor lock-in.

e. Loose coupling – separates application configuration and dependency from business logic

f. Reduces boiler plate code.

g. Allows cross-cutting configurations at a modular level.

h. Can run on a web server instead of an application server.

e. Uses best practices from the Design patterns – Single responsibility principle, dependency injection, factory pattern, template pattern, singleton pattern and prototype pattern.

For a typical Spring Application we need the following files:

1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.,
3. A XML file called Spring configuration file.
4. Client program that uses the function.