Spring boot

Spring boot jpa hibernate mysql crud example

Spring boot JPA CurdRepository implementation example

The Java Persistence API is a standard technology that lets you “map” objects to relational databases. The spring-boot-starter-data-jpa POM provides a quick way to get started. It provides the following key dependencies:

Hibernate: One of the most popular JPA implementations.

Spring Data JPA: Makes it easy to implement JPA-based repositories.

Spring ORMs: Core ORM support from the Spring Framework.

Spring Data JPA repositories are interfaces that you can define to access data. JPA queries are created automatically from your method names.

Spring Data repositories usually extend from the Repository or CrudRepository interfaces

Spring boot JPA starter (pom.xml)

Spring boot needs spring-boot-starter-data-jpa in pom.xml to load all JPA Configuration and your corresponding database driver, here i have used mysql dependency.

	
<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>com.candidjava.spring.boot</groupId>
	<artifactId>Spring-Boot-Jpa-mysql</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>helloworld-rest-hib-curd</name>
	<url>http://maven.apache.org</url>
	
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
	</parent>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    
    <dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
	</dependency>
	    
	    
	    
	   <!-- Tomcat embedded container-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-devtools</artifactId>
                    <optional>true</optional>
            </dependency> 
		

    </dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
    <finalName>Spring-Boot-Jpa-mysql</finalName>
  </build>
</project>

Extending CurdRepository (UserRepository.java)

Interface for generic CRUD operations on a repository for a specific type.

package com.candidjava.spring.repository;

import org.springframework.data.repository.CrudRepository;

import com.candidjava.spring.bean.User;
public interface UserRepository extends CrudRepository<User,Long> {

}

Hibernate and mysql configuration (application.yml)

spring:
datasource:
driver : com.mysql.jdbc.Driver
url : jdbc:mysql://localhost:3306/test3
username : root
passowrd : root
jpa:
show-sql : true
hibernate:
ddl-auto: update
dialect: org.hibernate.dialect.MySQL5Dialect
properties :

Simple Entity class (User.java)

Any classes annotated with @Entity, @Embeddable, or @MappedSuperclass are considered as JPA Entity Classes.

package com.candidjava.spring.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;


@Entity
@Table(name = "UserInfo")
//@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 private long id;

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

 private String name;


 public long getId() {
  return id;
 }

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

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

}

Launch as Spring boot (Application.java)

package com.candidjava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
 public static void main(String[] args) {
  SpringApplication.run(Application.class, args);
 }

}

UserController.java

package com.candidjava.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.service.UserService;

@RestController
@RequestMapping(value = {
 "/user"
})
public class UserController {
 @Autowired
 UserService userService;

 @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<User> getUserById(@PathVariable("id") long id) {
  System.out.println("Fetching User with id " + id);
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
  }
  return new ResponseEntity<User>(user, HttpStatus.OK);
 }

 @PostMapping(value = "/create", headers = "Accept=application/json")
 public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
  System.out.println("Creating User " + user.getName());
  userService.createUser(user);
  HttpHeaders headers = new HttpHeaders();
  headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
  return new ResponseEntity<Void> (headers, HttpStatus.CREATED);
 }

 @GetMapping(value = "/get", headers = "Accept=application/json")
 public List<User> getAllUser() {
  List<User> tasks = userService.getUser();
  return tasks;

 }

 @PutMapping(value = "/update", headers = "Accept=application/json")
 public ResponseEntity<String> updateUser(@RequestBody User currentUser) {
  System.out.println("sd");
  User user = userService.findById(currentUser.getId());
  if (user == null) {
   return new ResponseEntity<String> (HttpStatus.NOT_FOUND);
  }
  userService.update(currentUser, currentUser.getId());
  return new ResponseEntity<String> (HttpStatus.OK);
 }

 @DeleteMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> deleteUser(@PathVariable("id") long id) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  userService.deleteUserById(id);
  return new ResponseEntity<User> (HttpStatus.NO_CONTENT);
 }

 @PatchMapping(value = "/{id}", headers = "Accept=application/json")
 public ResponseEntity<User> updateUserPartially(@PathVariable("id") long id, @RequestBody User currentUser) {
  User user = userService.findById(id);
  if (user == null) {
   return new ResponseEntity<User> (HttpStatus.NOT_FOUND);
  }
  User usr = userService.updatePartially(currentUser, id);
  return new ResponseEntity<User> (usr, HttpStatus.OK);
 }
}

UserService.java

package com.candidjava.spring.service;

import java.util.List;

import com.candidjava.spring.bean.User;

public interface UserService {
 public void createUser(User user);
 public List<User> getUser();
 public User findById(long id);
 public User update(User user, long l);
 public void deleteUserById(long id);
 public User updatePartially(User user, long id);
}

UserServiceImpl.java

package com.candidjava.spring.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.candidjava.spring.bean.User;
import com.candidjava.spring.repository.UserRepository;

@Service
@Transactional
public class UserServiceImpl implements UserService {
 @Autowired
 UserRepository userRepository;

 public void createUser(User user) {
  // TODO Auto-generated method stub
  userRepository.save(user);
 }

 public List<User> getUser() {
  // TODO Auto-generated method stub
  return (List<User>) userRepository.findAll();
 }

 public User findById(long id) {
  // TODO Auto-generated method stub
  return userRepository.findById(id).get();
 }

 public User update(User user, long l) {
  // TODO Auto-generated method stub
  return userRepository.save(user);
 }

 public void deleteUserById(long id) {
  // TODO Auto-generated method stub
  userRepository.deleteById(id);
 }

 public User updatePartially(User user, long id) {
  // TODO Auto-generated method stub
  User usr = findById(id);
  usr.setCountry(user.getCountry());
  return userRepository.save(usr);
 }
}

Download

Download source code from my github account Click here