A little bit of Spring Boot
During the past week I’ve been learning and following a course of spring boot to build a simple REST api and connect it with postgreSql, also reviewing some concepts of React and how to create an App on slack and made the proper configuration to reach the service on your local machine with help of ngrok to create a http tunnel to communicate the service and finally after some struggles the little bot is responding successfully.
I’ve been creating a simple task Rest api with spring boot and here’s what i’ve learned, first of all you need to create a basic entity that is just a POJO (Plain Old Java Object) representing the data that can be persisted to de DB, every instance of entity represents a row in a table. You can declare an Entity with the @Entity annotation at class level, you also need an no args constructor and an Id.
The table annotation (@Table) is used to specify the table name, if it’s empty or doesn’t use the name of the entity and table will be the same.
Id annotation define a primary key for the entity and it uses @Generated value to set the type, it could be SEQUENCE, AUTO, TABLE or IDENTITY
There’s also another annotation like @Column that defines the properties of the column(length, nullable, unique etc..)
@Transient annotation is to make a non persistent field (values that can be calculated)
For every entity we need to create his own repository that is an interface that extends JpaRepository<T,idType> that accept generics and contain a lot of methods like find, search, save, delete etc…
We can also define Queries inside this interface like search by Title in this example.
Then we need to implement our controller and service.
@RestController just specify that it’s going to be a controller
@RequestMApping set the path for that service to be reached
@Autowired connects our controller with the service via Dependency Injection
Get, Post, Delete and Put Mapping are annotations to specify different behaviors like CRUD
@Path variable help us to get a value from the path, and @RequestBody to read a body form a POST method.
Finally our task service makes use of the repository that we create earlier and it’s used via dependency Injection with the @Autowired annotation in this part we can write business logic from each service.
So this is it for this week I’ve also need to continue with my Jpa Spring course to get a better understanding of how everything works and understand all the relations through different entities, also take a full course of PostgreSQL I need to have all fresh in my mind.