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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Getting Started With JPA/Hibernate
  • Spring Boot Centralized Logging with Graylog
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 4)
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 1)

Trending

  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots
  • A Simple, Convenience Package for the Azure Cosmos DB Go SDK
  • A Complete Guide to Modern AI Developer Tools
  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  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
74.9K 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
  • Spring Boot Centralized Logging with Graylog
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 4)
  • Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part 1)

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!