Skip to main content

Spring Boot Mysql Database Tutorial with Example Code - GET/POST/PUT/DELETE

 Learn how to connect to mysql database using spring boot framework. In this article you will learn the different types of @GetMapping/ @PostMapping / @PutMapping and @DeleteMapping Usages and their components @RestController, @Service, @Repository and @Entity.


Goto Spring Initializer https://start.spring.io/ and add the following dependencies like Spring web, JPA, lombok and mysql driver similar to below image




Generate the boilerplate code and open the project into your IDE.


Follow the below screenshot and create the respective packages to maintain your code easily.




Lets Create the follow classes

UserController.java

package com.hakeemit.database.controller;

import com.hakeemit.database.entity.User;
import com.hakeemit.database.entity.UserDetails;
import com.hakeemit.database.service.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserServices userServices;

    @GetMapping("/findAll")
    public List getAllUser(){
        return userServices.getAllUser();
    }

    @PostMapping("/add")
    public User add(@RequestBody UserDetails userDetails){
        return userServices.add(userDetails);
    }

    @PutMapping("/update")
    public User update(@RequestBody UserDetails userDetails){
        return userServices.update(userDetails);
    }

    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable int id){
        return userServices.delete(id);
    }
}


UserServices.java


package com.hakeemit.database.service;

import com.hakeemit.database.entity.User;
import com.hakeemit.database.entity.UserDetails;
import com.hakeemit.database.repositories.UserRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class UserServices {

    @Autowired
    private UserRepositories userRepositories;

    public List getAllUser(){
        return userRepositories.findAll();
    }

    public User add(UserDetails userDetails){
        User user = new User();
        user.setName(userDetails.getName());
        user.setGender(userDetails.getGender());
        user.setEmailId(userDetails.getEmailId());
        return userRepositories.save(user);
    }

    public User update(UserDetails userDetails){
        Optional user = userRepositories.findById(userDetails.getId());
        if(user.isPresent()) {
            user.get().setName(userDetails.getName());
            user.get().setGender(userDetails.getGender());
            user.get().setEmailId(userDetails.getEmailId());
            return userRepositories.save(user.get());
        }
        return null;
    }

    public String delete(int id){
        Optional user = userRepositories.findById(id);
        if(user.isPresent()) {
            userRepositories.delete(user.get());
            return "Deleted";
        }
        return "Failed to delete";
    }
}


UserRepositories.java


package com.hakeemit.database.repositories;

import com.hakeemit.database.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepositories extends JpaRepository {
}


User.java


package com.hakeemit.database.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Getter;
import lombok.Setter;

@Entity
@Getter
@Setter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String gender;
    private String emailId;

}


UserDetails.java

package com.hakeemit.database.entity;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserDetails {
    private int id;
    private String name;
    private String gender;
    private String emailId;
}


application.properties

spring.application.name=database

# ========== Database Configuration ==========
spring.datasource.url=jdbc:mysql://localhost:3306/tutorial?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=admin123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# ========== JPA Configuration ==========
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect

Watch the below video to understand the flow of code and for sending the payload details using 
postman
Video Tutorials


Comments

Popular posts from this blog

Gradle project sync failed. Basic functionality (e.g, editing, debugging) will not work properly.

Gradle is an open source build tool which help us to accelerate developer productivity. Go to Gradle Services website(http://services.gradle.org/distributions/) and download the latest version Download the latest version gradle-4.7-rc-1-all.zip ( Latest version while writing this article) and you can download greater than 4.7 if available and make sure the zip file contains "all" keyword (gradle-*.*-rc-*-all.zip). Go to your download location and unzip the downloaded file Android Studio > File >  Settings > Build, Execution, Deployment  Gradle Project-level settings -> Select Use local gradle distribution -> Select the unzip folder of downloaded gradle version -> Click OK button to exit from the Settings window. Please Wait until Gradle build completes and your problem have been resolved.   If gradle build failed, follow few more steps to get resolved Final step to resolve this error Go to your project -> Gradle script -...

How to Send Secured Data in Internet - Steganography

Image Description: Hackers Growth of Science and Technology finds innovative ways to find patches over attacks made by hacker.In the Internet there are millions of computer are interconnected by network.If some people want to share some personal things like bank accounts or premium login accounts through email or any other share media but hacker who is surfing anonymously in the Internet find the personal documents and trying to modify the original message as well utilizing the original message so that the receiver who receive fake message from hacker thought that the message sended by sender.. In order to confuse hackers technology made another innovation in new technique called "Steganography" What is Steganography? Steganography is new technology innovation which hides text messages in image,audio,text and video files To Make your data very securely just what you need to do is find the best steganography software from Internet and download it and then encrypt your me...

Spring Boot GraphQL Save, Update and Delete - Database MutationMapping

Learn how to get started with Graphql using spring boot framework. In this session, you will be learning like how to add the schema details and mapping the function and request payload with Graphql @MutationMapping into your controller class. So you can preform like Save, update and delete operation using graphql You need Spring web, JPA, Mysql, Lombok and Spring Graphql dependencies to your pom module. schema.graphqls (This file should be created inside the resources/graphql folder) type Query{ findAll: [User] userById(id: ID): User } type User{ id: ID name: String gender: String emailId: String } type Mutation{ addUser(userDetails: UserDetails): User updateUser(userDetails: UserDetails): User deleteUser(id: ID): String } input UserDetails{ id: ID name: String gender: String emailId: String } UserGQLController .java package com.hakeemit.graphql.controller; import com.hakeemit.graphql.entity.User; import com.hakeemit.gra...