Enterprise Java

Spring Hibernate Integration Example

In this post, we feature an example of Spring and Hibernate Integration.

Undoubtedly Spring and Hibernate are the most popular frameworks in the Java enterprise development world. Spring is a highly modular and lightweight framework offer integration with several other frameworks. Hibernate is one among them. Hibernate is the most popular Object-relational Mapping framework which has made database related operations very easy.

Spring Hibernate

In this article, we are going to study how to integrate both of these frameworks. Before that, I would suggest you read some articles to understand both of these frameworks. Some suggestions are listed below:

Spring

Hibernate

1. Introduction

Both Spring and Hibernate support annotation-based and XML based configuration. We are going to see how we can integrate both of these frameworks using Java-based configuration. For this example, I am using Java 8 and IntelliJ Idea as the development IDE.

2. Demo

In this tutorial, I am using Java’s inbuilt H2 database. We need to add below dependencies in pom.xml

pom.xml

<properties>
        <spring.version>5.1.6.RELEASE</spring.version>
        <hibernate.version>5.3.6.Final</hibernate.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version></dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.197</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-dbcp</artifactId>
            <version>9.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

This demo application offers a controller to fetch students from the H2 database. The controller is annotated with standard Spring annotation @RestController and offers an endpoint “/api/students”. Hibernate entity classes and repository classes are respectively using the appropriate annotations.

Below is the controller class,

SimpleController

@RestController
@RestController
@RequestMapping("/api")
public class SimpleController {
    @Autowired
    StudentService studentService;

    @RequestMapping(value = "/students", method = RequestMethod.GET)
    public @ResponseBody
    StudentResponse getStudents() throws Exception {
        StudentResponse response = new StudentResponse();
        response.setStudents(studentService.fetchAllStrudents());
        return response;
    }
}

In this demo exercise, I am using Hibernate’s criteria API to fetch the students from the database. Below is the sample,

StudentDao

@Repository
public class StudentDao {

    @Autowired
    private SessionFactory sessionFactory;

    public List getAllStudents() throws Exception{
        Session session = sessionFactory.getCurrentSession();
        CriteriaQuery query = session.getCriteriaBuilder().createQuery(Student.class);
        query.select(query.from(Student.class));
        return session.createQuery(query).getResultList();
    }

    public void saveStudent(Student student) {
        Session session = sessionFactory.getCurrentSession();
        session.save(student);
    }
}

Instead of XML based configuration, I am using Java-based configuration. Hibernate configuration is defined in the below class,

HibernateConfiguration

@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setAnnotatedPackages("com.jcg.entity");
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
        dataSource.setUsername("sa");
        dataSource.setPassword("sa");

        return dataSource;
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() {
        HibernateTransactionManager transactionManager
                = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    private final Properties hibernateProperties() {
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty(
                "hibernate.hbm2ddl.auto", "create-drop");
        hibernateProperties.setProperty(
                "hibernate.dialect", "org.hibernate.dialect.H2Dialect");

        return hibernateProperties;
    }
}

Along with Hibernate Configuration, we need to add configuration class to load different beans and an application initializer class to load our application.

WebConfig

@Configuration
@EnableWebMvc
@ComponentScan("com.jcg")
public class WebConfig {
    @Bean
    public StudentService studentService() {
        return new StudentService();
    }

    public StudentDao studentDao() {
        return new StudentDao();
    }
}

This class enables the annotation-based component scan and provides bean definition.

ApplicationInitialize

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[] {
                WebConfig.class
        };
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] {
                "/*"
        };
    }
}

This is like web.xml which defines the default path and root configuration of our application.

This is a classic Spring application, hence to run we have to build a deployable war file and manually deploy in the Tomcat server. For this to happen, add a build configuration in pom.xml as below,

 
<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>

Package the solution into the war file. A packaged war file can be found under the target folder of your project.

Download the Tomcat web server and place the war file under <tomcat home directory>/webapps.

Go to command prompt and navigate to <tomcat home directory>/bin and run statup.bat

Once Tomcat is successfully started, access http://localhost:8080/api/students to see student details as a JSON.

Output: When you access the API /api/students offered by the demo application, you will receive an output similar to below,

{"students":[{"id":1,"firstName":"Santosh","lastName":"S","year":"1970"}]}

3. Download the Source Code

Download
You can download the full source code of this example here: Spring Hibernate Integration Example

Santosh Balgar

He is a Software Engineer working in an industry-leading organization. He has completed his bachelors from Visweswaraya Technological University. In his career, he has worked in designing and implementing various software systems involving Java/J2EE, Spring/ Spring Boot, React JS, JQuery, Hibernate and related database technologies. He loves to share his knowledge and always look forward to learning and explore new technologies. He loves to spend his free time with his family. He enjoys traveling and loves to play cricket.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button