Spring Boot + Hibernate CRUD Example

Let us see an example of spring boot + hibernate integration example with Crud (Create, Read, Update and Delete) operations.

In the below example we are going to use Spring jpa and CrudRepository.

Annotations used in the below example:

@EnableJpaRepositories: Used to enable JPA repositories.
@EnableTransactionManagement:  Used for enabling transaction management, similar to <tx>.

Crud Repository:
In the below example, we have used crud repository, let us understand about this repository. The CrudRepository provides CRUD functionality for the Entity class. It has in-build functions for performing CRUD operations which allow us to write less code and use the functions directly from this repository.

public interface {{InterfaceName}} extends CrudRepository<Entity, Long>{
}

Now let us see an example of CRUD operations with Spring Boot and Hibernate. (You can Download the Code Here)

Structure:

pom.xml

<?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>spring.first</groupId>
    <artifactId>SpringBootHibernate</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

  <!-- <dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
  </dependency> -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
    
</project>

application.properties:

spring.datasource.url = jdbc:mysql://localhost:3306/employee
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.hibernate.ddl-auto= update
spring.jpa.show-sql = true
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

com.javainfinite.model

package com.javainfinite.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;

/**
 *
 * @author vikram
 */
@Entity
public class Employee{ 
    @Id
    @GeneratedValue
    private long id;
    private String empName;
    private String empDept;

    public long getId() {
        return id;
    }

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

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public String getEmpDept() {
        return empDept;
    }

    public void setEmpDept(String empDept) {
        this.empDept = empDept;
    }
}

com.javainfinite.EmployeeDAO

package com.javainfinite.DAO;

import com.javainfinite.model.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author vikram
 */

@Transactional
public interface EmployeeDAO extends CrudRepository<Employee, Long> {
    
}

com.javainfinite.application.controller

package com.javainfinite.Application.Controller;

import com.javainfinite.DAO.EmployeeDAO;
import com.javainfinite.model.Employee;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author vikram
 */
@RestController
public class EmployeeController{
    
    @Autowired
    private EmployeeDAO employeeDAO;
    
    @RequestMapping(value="/getAllEmployees", method=RequestMethod.GET)
    
    public List<Employee> getAllEmployees(){
        List<Employee> empList = (List<Employee>) employeeDAO.findAll();
        System.out.println(empList.size());
        return empList;
    }
    
    @RequestMapping(value="/saveEmployee", method=RequestMethod.POST)
    public Employee saveEmployee(@RequestBody Employee employee){
        Employee emp = employeeDAO.save(employee);
        return emp;
    }
    
    @RequestMapping(value="/getById/{id}", method=RequestMethod.GET)
    public Employee getByIdEmployee( @PathVariable("id") long id){
        Employee emp = employeeDAO.findOne(id);
        return emp;
    }
    
    @RequestMapping(value="/updateEmployee/{id}", method=RequestMethod.PUT)
    public Employee updateEmployee(@PathVariable("id") long id, @RequestBody Employee employee){
        Employee emp = employeeDAO.findOne(id);
        emp.setEmpName(employee.getEmpName());
        emp.setEmpDept(employee.getEmpDept());
        Employee savedEmp = employeeDAO.save(emp);
        return savedEmp;
    }
    
    @RequestMapping(value="/deleteEmployee/{id}", method=RequestMethod.DELETE)
    public void deleteEmployee(@PathVariable("id") long id){
         employeeDAO.delete(employeeDAO.findOne(id));
    }
}

com.javainfinite.application

 */
package com.javainfinite.Application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 *
 * @author vikram
 */
@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.javainfinite.DAO")
@EnableTransactionManagement
@EntityScan(basePackages="com.javainfinite")
public class Application {
    
    public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
    }
}

 Saving Employee – First Record

Saving Employee – Second Record

Get all Employees – To List Entered Both Records

Get By Id:

Updating Record

After Update Getting By Id:

Deleting a Record:

 

After Deleting a Record

You can Download the Code Here – Please modify the database properties.

 

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *