DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Getting Started With JPA/Hibernate
  • How Spring and Hibernate Simplify Web and Database Management
  • A Practical Guide to Creating a Spring Modulith Project
  • How To Create a Homescreen Widget in Android

Trending

  • Setting Up a Data Catalog With Azure Purview and Collibra: What Three Attempts Taught Me
  • Retesting Best Practices for Agile Teams: A Quick Guide to Bug Fix Verification
  • Hallucination Has Real Consequences — Lessons From Building AI Systems
  • The ORM Is Over: AI-Written SQL Is the New Data Access Layer
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring and Hibernate Application with Zero XML

Spring and Hibernate Application with Zero XML

By 
Siva Prasad Reddy Katamreddy user avatar
Siva Prasad Reddy Katamreddy
·
Feb. 23, 11 · Interview
Likes (7)
Comment
Save
Tweet
Share
75.2K Views

Join the DZone community and get the full member experience.

Join For Free
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

Spring Framework XML application Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • Getting Started With JPA/Hibernate
  • How Spring and Hibernate Simplify Web and Database Management
  • A Practical Guide to Creating a Spring Modulith Project
  • How To Create a Homescreen Widget in Android

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook