Spring 5 + Hibernate 5 integration Only annotations without xml configuration

Learn How to Create a Spring 5 + Hibernate 5 application using Only annotations without xml configuration in really easy way.

Let’s Begin Coding

1. Final Project Structure – will look like this

spring-hibernate-with-annotations-project-structure

2. Add jar dependencies to pom.xml

In this project we will use Spring 5, Hibernate 5 and mySql DB stack.

To use the above technology stack add the following dependencies in your pom.xml file as below.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>SpringHibernate</groupId>
    <artifactId>com.pt</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/
             org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/
             org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/
             mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/
             org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.11.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/
             org.apache.commons/commons-dbcp2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.7.0</version>
        </dependency>

        </dependency>
    </dependencies>

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
    </build>

</project>

2. Create Entity Class

Employee.java Entity Class

package com.pt.entities;

import javax.persistence.*;

@Entity
@Table(name = "EMPLOYEE")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "address")
    private String address;

    public Employee() {}

    public Employee(int id, String firstName, 
                    String lastName, String address) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId( int id ) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName( String first_name ) {
        this.firstName = first_name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName( String last_name ) {
        this.lastName = last_name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

3. Create DAO Layer

Create Data Access Object layer:
1. Dao Interface
2. Dao Implementation Class

EmployeeDao.java Interface

package com.pt.dao;

import com.pt.entities.Employee;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeDao {

        void add(Employee employee);

}

EmployeeDaoImpl.java Class

package com.pt.dao;

import com.pt.entities.Employee;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void add(Employee employee) {
        sessionFactory.getCurrentSession().save(employee);
    }
}

4. Create Service Layer

Create Service layer:
1. Service Interface
2. Service Implementation Class

EmployeeService.java Interface

package com.pt.services;

import com.pt.entities.Employee;


public interface EmployeeService {

    void add(Employee employee);

}

EmployeeServiceImpl.java Class

package com.pt.services;

import com.pt.dao.EmployeeDao;
import com.pt.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    public EmployeeDao employeeDao;

    @Transactional
    @Override
    public void add(Employee employee) {
        employeeDao.add(employee);
    }
}

5. Create db.properties File

db.properties

# MySQL properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/testdb
db.username=root
db.password=root

# Hibernate properties
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

6. Create Configs Class File

AppConfig.Java Class

package com.pt.configs;

import com.pt.entities.Employee;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
@ComponentScans(value = {
        @ComponentScan("com.pt.dao"),
        @ComponentScan("com.pt.services")
})

public class AppConfig {

        @Autowired
        private Environment env;

        @Bean
        public DataSource getDataSource() {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(env.getProperty("db.driver"));
            dataSource.setUrl(env.getProperty("db.url"));
            dataSource.setUsername(env.getProperty("db.username"));
            dataSource.setPassword(env.getProperty("db.password"));
            return dataSource;
        }

        @Bean
        public LocalSessionFactoryBean getSessionFactory() {
            LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
            factoryBean.setDataSource(getDataSource());

            Properties props=new Properties();
            props.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
            props.put("hibernate.dialect",env.getProperty("hibernate.dialect"));
            props.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
            factoryBean.setHibernateProperties(props);
            factoryBean.setAnnotatedClasses(Employee.class);
            return factoryBean;
        }

        @Bean
        public HibernateTransactionManager getTransactionManager() {
            HibernateTransactionManager transactionManager = new HibernateTransactionManager();
            transactionManager.setSessionFactory(getSessionFactory().getObject());
            return transactionManager;
        }
}

7. Last – Create main() method Class File

StartApp.java Class

package com.pt;

import com.pt.configs.AppConfig;
import com.pt.entities.Employee;
import com.pt.services.EmployeeService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.sql.SQLException;

public class StartApp {

    public static void main(String[] args) throws InterruptedException, SQLException {
        System.out.println("This is the start of the PT Spring Hibernate application");
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(AppConfig.class);

        EmployeeService employeeService = context.getBean(EmployeeService.class);

        // Add Employee
        employeeService.add(new Employee(1,"Mak", "S", "mak@pt.com"));

        context.close();
    }
}

OUTPUT

console log

"C:\Program Files\Java\jdk1.8.0_201\bin\java.exe" ...
This is the start of the PT Spring Hibernate application
Feb 13, 2020 10:22:46 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.4.11.Final}
Feb 13, 2020 10:22:47 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Feb 13, 2020 10:22:54 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
Feb 13, 2020 10:22:57 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: insert into EMPLOYEE (address, first_name, last_name) values (?, ?, ?)

Process finished with exit code 0

In Database – The record is successfully inserted in the database.

mysql> select * from employee;
+----+------------+------------+-----------+
| id | address    | first_name | last_name |
+----+------------+------------+-----------+
|  1 | mak@pt.com | Mak        | S         |
+----+------------+------------+-----------+
1 row in set (0.00 sec)

Summary

In this tutorial, we learnt how to Create a Spring 5 + Hibernate 5 application using Only annotations without xml configuration in really easy way.
Hope you liked it !