Tuesday, September 14, 2010

Using Hibernate, Spring, Maven, oracle all together

This tutorial will give an overview how can you wire up spring and hibernate together. The spring framework comes with ability to inject dependencies through the spring configuration file, we can leverage that to create the hibernate SessionFactory. Some code samples are given below. Also, we'll use the java persistence api so that we don't need to specify the hibernate mapping files.

The User class :

public class User {

private Long id;
private String name;
private String password;

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "user_id_seq")
@SequenceGenerator(name="user_id_seq", sequenceName = "MY_USER_SEQ")
public Long getId() {
return id;
public void setId(Long id) {
this.id = id;

public String getName() {
return name;
Replace the GeneratedValue annotation with strategy=GenerationType.AUTO if you are using any other database and no need to have sequencegenerator.

The DAO interface and implementation :

public interface UserDAO {

public void saveUser(User user) ;
public List<User> listUser() ;

public class UserDAOImpl implements UserDAO {

private HibernateTemplate hibernateTemplate;

public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);

public void saveUser(User user) {

public List<User> listUser() {
return hibernateTemplate.find("from User");

The main application class:

public class App
public static void main( String[] args )

BeanFactory factory = new XmlBeanFactory(
new ClassPathResource("application-context.xml"));

UserDAO dao = factory.getBean("myUserDAO");

User user=new User();

Spring configuration file : application-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:user/password@localhost:1521:XE"/>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<property name="hibernateProperties">
<prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>

<bean id="myUserDAO" class="ca.co.fusionapp.dao.UserDAOImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
The above configuration uses setter dependency injection (i.e, the UserDAO has a setSessionFactory method, which sets up the hibernate session factory).

Download the entire code from here, which contains the pom.xml and run the above example using following command : mvn clean compile exec:java -e

I've oracle express installed and set up a username/password which needs to be updated in application-context.xml file.