SQL Zone is brought to you in partnership with:

I am Siva, a passionate java developer, open source enthusiast, blogger. I like to cover Java, Struts, Spring, Hibernate, Ajax Tutorials, How-To's and Best Practices. Sivaprasadreddy is a DZone MVB and is not an employee of DZone and has posted 35 posts at DZone. You can read more from them at their website. View Full User Profile

Spring and Hibernate Application with Zero XML

02.23.2011
| 17611 views |
  • submit to reddit
The Spring framework came up with annotation support since 2.5 version which eases development.
Whether the annotation based approach, or XML approach is better, is depends on the project and your personal preference. Let us see how we can write a Simple Application using Spring and Hibernate using annotations, no xml at all.

The configuration for JDBC datasource and Hibernate properties:

application.properties

################### JDBC Configuration ##########################
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:file:db/SivaLabsDB;shutdown=true
jdbc.username=sa
jdbc.password=

################### Hibernate Configuration ##########################
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true

We can instantiate ApplicationContext from a Java file using the @Configuration annotation.

AppConfig.java

package com.sivalabs.springmvc.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;

/**
* @author SivaLabs
*
*/
@Import({RepositoryConfig.class})
@Configuration
public class AppConfig
{
//<context:property-placeholder location="classpath:application.properties"></context:property-placeholder>
@Bean
public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
{
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("application.properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}

Here @Import({RepositoryConfig.class}) is the same as the xml version:  <import resource="applicationContext-dao.xml"></import>

package com.sivalabs.springmvc.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
* @author SivaLabs
*
*/
@Configuration
public class RepositoryConfig
{
//${jdbc.driverClassName}
@Value("${jdbc.driverClassName}") private String driverClassName;
@Value("${jdbc.url}") private String url;
@Value("${jdbc.username}") private String username;
@Value("${jdbc.password}") private String password;

@Value("${hibernate.dialect}") private String hibernateDialect;
@Value("${hibernate.show_sql}") private String hibernateShowSql;
@Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto;

@Bean()
public DataSource getDataSource()
{
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
{
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}

@Bean
@Autowired
public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory)
{
HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
return hibernateTemplate;
}

@Bean
public AnnotationSessionFactoryBean getSessionFactory()
{
AnnotationSessionFactoryBean asfb = new AnnotationSessionFactoryBean();
asfb.setDataSource(getDataSource());
asfb.setHibernateProperties(getHibernateProperties());
asfb.setPackagesToScan(new String[]{"com.sivalabs"});
return asfb;
}

@Bean
public Properties getHibernateProperties()
{
Properties properties = new Properties();
properties.put("hibernate.dialect", hibernateDialect);
properties.put("hibernate.show_sql", hibernateShowSql);
properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);

return properties;
}

}
Create an Entity User as follows:

package com.sivalabs.springmvc.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
* @author SivaLabs
*
*/

@Entity
public class User
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String address;

public User()
{
}
public User(Integer id, String name, String address)
{
this.id = id;
this.name = name;
this.address = address;
}

@Override
public String toString()
{
return "User [address=" + address + ", id=" + id + ", name=" + name+ "]";
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}

}

Create UserRepository to perform DB operations using Hibernate.

package com.sivalabs.springmvc.repositories;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sivalabs.springmvc.entities.User;

/**
* @author SivaLabs
*
*/

@Transactional
@Repository
public class UserRepository
{
@Autowired
private HibernateTemplate hibernateTemplate;

public List<User> getAllUsers()
{
return this.hibernateTemplate.loadAll(User.class);
}

public Integer createUser(User user)
{
User mergeUser = this.hibernateTemplate.merge(user);
return mergeUser.getId();
}
}


Create a UserService class which is responsible for performing User operations.

package com.sivalabs.springmvc.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sivalabs.springmvc.entities.User;
import com.sivalabs.springmvc.repositories.UserRepository;

/**
* @author SivaLabs
*
*/

@Service
public class UserService
{
@Autowired
private UserRepository userRepository;

public List<User> getAllUsers()
{
return this.userRepository.getAllUsers();
}

public Integer createUser(User user)
{
return this.userRepository.createUser(user);
}
}

Now let us create ApplicationContext from AppConfig.java and test the functionality.

package com.sivalabs.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sivalabs.springmvc.entities.User;
import com.sivalabs.springmvc.services.UserService;

public class ContainerTest
{
public static void main(String[] args)
{
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.sivalabs");//This will load the configured components UserService, UserRepository,
ctx.refresh();

System.out.println(ctx);
UserService userService = ctx.getBean("userService", UserService.class);

List<User> allUser = userService.getAllUsers();
for (User u : allUser)
{
System.out.println(u);
}

User user = new User(null, "K.siva reddy", "hyderabad");
Integer id = userService.createUser(user);
System.out.println("Newly created User Id="+id);
allUser = userService.getAllUsers();
for (User u : allUser)
{
System.out.println(u);
}
}

}

See how application development is much more easier now with Annotations.

From : http://sivalabs.blogspot.com/2011/02/springhibernate-application-with-zero.html

Published at DZone with permission of Sivaprasadreddy Katamreddy, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Nicolas Frankel replied on Wed, 2011/02/23 - 5:25am

package com.sivalabs.springmvc.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;

/**
* @author SivaLabs
*
*/
@Import({RepositoryConfig.class})
@Configuration
public class AppConfig
{
//<context:property-placeholder location="classpath:application.properties"></context:property-placeholder>
@Bean
public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer()
{
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("application.properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}

Here @Import({RepositoryConfig.class}) is the same as the xml version:  <import resource="applicationContext-dao.xml"></import>

 

I am amazed to see how far this XML-bashing trend go: should we be so happy to have replaced a single line XML with 1 line of compiled Java annotation? What's the damn point?

XML is not bad when you have the right tool. Just use Spring IDE and be done with it!

PS: sorry, your post could be interesting but I couldn't muster the courage to get past this part...

Quentin Le Henaff replied on Wed, 2011/02/23 - 10:17am

Good article. I used this in order to "by-pass" the main configuration for the test configuration ; this technique may be usefull and cleaner. Thx

Sivaprasadreddy... replied on Wed, 2011/02/23 - 11:49am in response to: Nicolas Frankel

 

I agree with you.

I missed to convey my main intention of going to use Annotation approach entirely instead of simple xml based approach.

Here it is:

I had a discussion with one of my friend about extending PropertyPlaceholderConfigurer and provide additional utility methods like JConfig's centralized Configuration manager.
All over the Annotation based Spring examples use xml based PropertyPlaceholderConfigurer configuration. So I thought of just telling there is a way to configure customized PropertyPlaceholderConfigurer through Annotations.

I am neither fan of Annotations nor XML. If you ask me to choose the approach, I will choose XML for non-frequently changing configuration and Annotations for Controller mappings and all.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.