Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring and Hibernate Application with Zero XML

DZone's Guide to

Spring and Hibernate Application with Zero XML

Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

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

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}