Before we move on to creating the project, I will briefly explain what the technologies Spring Boot, JPA and MySQL.
are.With these 3 technologies, we can develop robust, scalable and high-performance web applications.
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:
We will be configuring some things on the left side, such as:
In Project Metadata you will go by:
On the right side you will have the dependencies of our project, we need to add 3, namely:
In the end it will look like this:
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.
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:
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.
In my database I have a simple table called users in which there are 2 fields:
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 }
Now that we have our entity developed, we need to create our Repositories that will implement JPA to perform manipulations in the Database.
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:
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:
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:
The article repository can be found at this link: Project Repository
A hug and good studies! Until later.
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