"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to start a Spring Boot + JPA + MySQL application

How to start a Spring Boot + JPA + MySQL application

Published on 2024-08-28
Browse:416

Before we move on to creating the project, I will briefly explain what the technologies Spring Boot, JPA and MySQL.

are.
  • Spring Boot: is a Java framework used to simplify the development of Spring applications, allowing the creation of standalone applications, which can be executed with a simple command, without the need for complex configuration.
  • JPA: Java Persistence API is a Java specification that defines how Java objects should be mapped to relational databases (ORM).
  • MySQL: World famous open source Relational Database Management System (RDBMS). It is widely used to store, organize and manage large volumes of data in web and enterprise applications.

With these 3 technologies, we can develop robust, scalable and high-performance web applications.

Project Creation

We will be creating the project in an online tool called: Spring Initializr which facilitates the creation of Spring Boot projects.

When you enter the URL, you will see a screen like this:

Como iniciar um aplicativo Spring Boot   JPA   MySQL

We will be configuring some things on the left side, such as:

  • Project Type: Maven
  • Language: Java
  • Spring Boot version: 3.3.2

In Project Metadata you will go by:

  • Group: br.com.(ex: br.com.josemarinho)
  • Artifact and Name: spring-jpa-mysql
  • Description: Project using Spring Boot, JPA and MySQL
  • Package name: automatically generated based on Group and Artifact.
  • Packaging: Jar
  • Java: 17

On the right side you will have the dependencies of our project, we need to add 3, namely:

  • Spring Web
  • Spring Data JPA
  • MySQL Driver

In the end it will look like this:

Como iniciar um aplicativo Spring Boot   JPA   MySQL

After configuration, just press the Generate button, where you will start downloading a Zip containing all the project directories/files. Afterwards, just unzip and open in your preferred IDE.

First run

As soon as you open the project and try to run the program, it will report a run-time error saying the following:

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

This occurs because Spring Boot cannot automatically configure a DataSource for the application. Shall we configure?

In the project there will be a directory called resources, within this directory there are some files, among them a file called application.properties which is where the settings of a spring boot project are located. I like to use its YAML/YML version, so just delete this file and create another one called application.yml, looking like this:

Como iniciar um aplicativo Spring Boot   JPA   MySQL

Let's define the url where our app will connect, driver, username and password:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: username
    password: password
    url: jdbc:mysql://127.0.0.1:3306/seu_banco_de_dados

In application.properties it would look like this:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://localhost:3306/seu_banco_de_dados

Okay, now just run the project again and you will see output like this.

Como iniciar um aplicativo Spring Boot   JPA   MySQL

Entity Creation

In my database I have a simple table called users in which there are 2 fields:

  • id: primary key integer auto increment
  • user: varchar(255)

Como iniciar um aplicativo Spring Boot   JPA   MySQL

With it, we will take the first step to map this table in a Java context, creating an Entity. To do this, create a class called User, at the end it should look like this:

@Entity
@Table(name = "usuarios")
public class Usuario {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String usuario;

    // Getters e Setters
}
  • @Entity: Marks the class as a JPA entity. This tells JPA that the class should be persisted in a database.
  • @Table(name = "product"): Specifies the name of the table in the database to which the entity is mapped. If this annotation is not provided, JPA assumes that the table name is the same as the class name.
  • @Id: Indicates that the field is the entity's primary key.
  • @GeneratedValue: Indicates the strategy that we will generate the values, in this case we choose that the database itself will automatically generate them for us, the default is GenerationType.AUTO.

Now that we have our entity developed, we need to create our Repositories that will implement JPA to perform manipulations in the Database.

Creation of Repositories using JPA

To start, create an interface called UsuarioRepositorio, this interface will inherit the characteristics of JpaRepository passing two generic values, the first is entity and the second is Id type. We can't help but forget to annotate the class with the @Repository annotation, looking like this:

@Repository
public interface UsuarioRepositorio extends JpaRepository { }

JpaRepository is a Spring Data JPA interface that provides several ready-made methods to perform data access operations in an application, such as findAll(), which returns all data from a given database table. At the end of the article I will leave some links talking more about.

We already have enough to perform some queries, let's create an entry point in our application to see this data.
Create a controller called: UsuariosController.
In it we will annotate it with 2 annotations: @RestController and @RequestMapping("/v1/usuarios") to map the route of our controller

Let's perform dependency injection on the UsuarioRepository and create a GET endpoint to obtain the data from the controller.

In the end it will look like this:

@RestController
@RequestMapping("/v1/usuarios")
public class UsuarioController {

    private UsuarioRepositorio usuarioRepositorio;

    public UsuarioController(UsuarioRepositorio usuarioRepositorio) {
        this.usuarioRepositorio = usuarioRepositorio;
    }

    @GetMapping()
    public ResponseEntity getUsuarios() {
        return ResponseEntity.status(HttpStatus.OK).body(usuarioRepositorio.findAll());
    }
}

Note that I am using the findAll() method that I mentioned above in the repository.

In my database table, I already have some data. Doing a simple query will give you the following result:

Como iniciar um aplicativo Spring Boot   JPA   MySQL

We saw that we have 3 data in the table.

After saving the content of the controller and running the project again, when we make a GET request at the url localhost:8080/v1/usuarios, the following result will come:

Como iniciar um aplicativo Spring Boot   JPA   MySQL

We see that the result that was retrieved when performing a database query was exactly the same when making a GET request in our application thanks to JPA and Spring Boot.

We have reached the end of another post. I'll be leaving some reference links:

  • Jpa Repository
  • Generated Value Annotation
  • MySQL JPA Driver
  • Spring Boot YAML vs Properties
  • Spring Data JPA

The article repository can be found at this link: Project Repository

A hug and good studies! Until later.

Release Statement This article is reproduced at: https://dev.to/iamjose/como-iniciar-um-aplicativo-spring-boot-jpa-mysql-2nl4?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3