Spring Boot + Mysql + CrudRepository Example | Java Inspires

#JavaInspires

Spring Boot + Mysql + CrudRepository Example




Project Folder 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>com.javainspires</groupId>
 <artifactId>CRUDRepositorySB</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>CRUDRepositorySB</name>
 <description>Demo project for Spring Boot With CrudRepository</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.2.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <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>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

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


</project>

application.properties
# Database
spring.datasource.driver = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/dev_db
spring.datasource.username = root
spring.datasource.password = root


spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect




User.java
package com.javainspires.springboot.crud.entity;

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

@Entity
@Table(name = "User")
public class User {

 @Id
 private String userId;
 @Column(name = "UserName")
 private String userName;
 @Column(name = "Password")
 private String password;
 @Column(name = "Age")
 private int age;

 public User() {
  super();
  // TODO Auto-generated constructor stub
 }

 public User(String userId, String userName, String password, int age) {
  super();
  this.userId = userId;
  this.userName = userName;
  this.password = password;
  this.age = age;
 }

 public String getUserId() {
  return userId;
 }

 public void setUserId(String userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

}

UserController.java
package com.javainspires.springboot.crud.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javainspires.springboot.crud.entity.User;
import com.javainspires.springboot.crud.service.UserService;

@RestController
@RequestMapping(path = "/user")
public class UserController {

 @Autowired
 UserService userService;

 @GetMapping
 public String check() {
  return "Hi, Welcome..";
 }

 @GetMapping(path = "/getusers")
 public List<User> getUsers() {
  return userService.getUsers();
 }

 @GetMapping(path = "/getuserbyid/{id}")
 public List<User> getUserById(@PathVariable(name = "id") String userId) {
  List<User> userList = new ArrayList<>();
  userList.add(userService.getUserById(userId));
  return userList;
 }

 @PostMapping(path = "/adduser")
 public String addUser(@RequestBody User user) {
  if (userService.addUser(user)) {
   return "User (userId=" + user.getUserId() + ") added successfully";
  } else {
   return "User (userId=" + user.getUserId() + ") failed to add";
  }
 }

 @DeleteMapping(path = "/deleteuser/{id}")
 public String deleteUser(@PathVariable("id") String userId) {
  if (userService.deleteUser(userId)) {
   return "User (userId=" + userId + ") deleted successfully";
  } else {
   return "User (userId=" + userId + ") failed to delete";
  }
 }
}



UserService.java
package com.javainspires.springboot.crud.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

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

import com.javainspires.springboot.crud.entity.User;
import com.javainspires.springboot.crud.repository.IUserRepository;

@Service
public class UserService {

 @Autowired
 IUserRepository userRepository;

 public List<User> getUsers() {
  List<User> userList = new ArrayList<>();
  userRepository.findAll().forEach(userList::add);
  return userList;
 }

 public User getUserById(String userId) {
  Optional<User> opUser = userRepository.findById(userId);
  if (opUser.isPresent()) {
   return opUser.get();
  } else {
   return null;
  }
 }

 public boolean addUser(User user) {
  if (userRepository.save(user) != null) {
   return true;
  } else {
   return false;
  }
 }

 public boolean deleteUser(String userId) {
  if (userRepository.findById(userId) != null) {
   userRepository.deleteById(userId);
   return true;
  } else {
   return false;
  }
 }

}

IUserRepository.java
package com.javainspires.springboot.crud.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.javainspires.springboot.crud.entity.User;

@Repository
public interface IUserRepository extends CrudRepository<User, String> {

}

CrudRepositorySbApplication.java
package com.javainspires.springboot.crud;

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

@SpringBootApplication
public class CrudRepositorySbApplication {

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

Thank You....



4 Comments

Previous Post Next Post