Spring Boot REST JPA and MySQL

In this tutorial you will learn how to create a Java web application using Spring Boot REST JPA and MySQL.

What is JPA? Java Persistence API, Java Persistence API. It is a set of definitions and protocols (interface) developed for Java EE. It is used to map and persist data in a relational database. Closely tied to JPA is hibernate, which is a framework that can implement JPA specifications.

What is MySQL? It is a database management system (DBMS) and through it you can perform CRUD (Create, Read, Update and Delete) operations on a relational database.

Create Database

When creating the local database, I have chosen the official MySQL software, although there are many programs that we can use free of charge, such as XAMP or MariaDB.

We will start with the installation of the MySQL Installer program (installer that will help configure the MySQL server) and MySQL Workbench (database client), which can be downloaded from its official website at the following addresses:

MySQL Installer: https://dev.mysql.com/downloads/installer/

MySQL Workbench: https://dev.mysql.com/downloads/workbench/

If you have doubts when installing MySQL, I recommend this tutorial: https://clicizquierdo.com/cursos-y-tutoriales/bases-de-datos/como-instalar-mysql-y-mysql-workbench/

Once the programs are installed, run MySQL Workbench and create a simple database (or schema) with a table and three fields. The sql for its creation is as follows:

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `username` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Add some test records to the users table.

Create project

Go to File -> New -> Project y elige Spring Boot -> Spring Boot Starter. Press Next.

Then fill in the details for the project and press Next:

Spring Boot REST JPA and MySQL

Then check the boxes Spring Web Services, Spring Web Starter, MySQL Driver y Spring Data JPA. Press Finish:

Spring Boot, REST, JPA y MySQL

Start the application (running the project as Spring Boot App) and watch the output in the Eclipse console. There are mistakes:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

The application is searching for connection parameters. To do this, enter the following lines in the application.properties file:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=1234

Run the application again and notice that the errors in the console have disappeared.


Classes to develop

A continuación añado las clases con el código necesario y el orden en el que se deben crear:

User.java (Class that defines the fields and attributes of the users table of our database)

package es.rosamarfil.jpa.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

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

	private static final long serialVersionUID = 1L;
	
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
    
    @Column(name = "name")
	private String name;

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


	public User() {
		super();
	}
	
	public User(Long id, String name, String username) {
		super();
		this.id = id;
		this.name = name;
		this.username = username;
	}

	public String getName() {
		return name;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

UserRepository.java (Repository interface that allows us to perform operations on the database)

package es.rosamarfil.jpa.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import es.rosamarfil.jpa.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

}

UserRestController.java (REST service operations controller with a defined UserRepository instance. In the comments for each operation, you have an example of the URLs and data to use)

package es.rosamarfil.jpa.controller;

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

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
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.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 es.rosamarfil.jpa.entity.User;
import es.rosamarfil.jpa.repository.UserRepository;

@RestController
@RequestMapping("/api")
public class UserRestController {

	@Autowired
	UserRepository userRepository;

	// Get All Users
	// URL: http://localhost:8080/api/users/1
	@GetMapping("/users")
	public List<User> getAllUsers() {
		return userRepository.findAll();
	}

	// Create a new User
	// URL: http://localhost:8080/api/createUser
	// Object json: {"name":"Rosa3333","username":"Marfi3333l"}
	@PostMapping("/createUser")
	public User createUser(@Valid @RequestBody User user) {
		return userRepository.save(user);
	}

	// Get a User by id
	// URL: http://localhost:8080/api/users/1
	@GetMapping("/users/{id}")
	public User getNoteById(@PathVariable(value = "id") Long id) {
		return userRepository.findById(id).orElse(null);
	}

	// Update a User
	// URL: http://localhost:8080/api/updateUser/1
	// Object json: {"name":"RosaUpdate","username":"Marfil"}
	@PutMapping("/updateUser/{id}")
	public User updateUser(@PathVariable(value = "id") Long id, @Valid @RequestBody User userDetails) {

		User user = userRepository.findById(id).orElse(null);

		user.setName(userDetails.getName());
		user.setUsername(userDetails.getUsername());

		User updatedNote = userRepository.save(user);
		return updatedNote;
	}

	// Delete a User
	// URL: http://localhost:8080/api/deleteUser/6
	@DeleteMapping("/deleteUser/{id}")
	public ResponseEntity<?> deleteUser(@PathVariable(value = "id") Long id) {
		
		User note = userRepository.findById(id).orElse(null);

		userRepository.delete(note);

		return ResponseEntity.ok().build();
	}
}



SbjpaMyqlApplication.java (Main class that runs our application. This is automatically self-generated when creating the project with Spring Boot. In this case we have added the @EnableJpaAuditing annotation)

package es.rosamarfil.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@EnableJpaAuditing
@SpringBootApplication
public class SbjpaMyqlApplication {

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

}


After all the classes are created, run the application and test the created services.

All the code developed is part of the BackEnd development of an application. In other tutorials we can access these services from an Angular Fron-End application. I hope this tutorial Spring Boot REST JPA and MySQL has been useful for you

Thanks for reading me!

You may also like...

Leave a Reply

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