Kako izraditi API za odmor pomoću Spring Boota koristeći MySQL i JPA

Pozdrav svima! Posljednjih godinu dana učim JavaScript za web-razvoj s punim slogovima. Za promjenu, počeo sam svladavati Javu - moćan objektno orijentirani jezik.

U tom sam slučaju pronašao vrlo čist i elegantan okvir nazvan Spring Boot za izgradnju pozadine.

Prije toga, u razvoju JavaScript-a, koristio sam:

  1. Mongoose - ORM (objektno relacijsko mapiranje) za Mongo DB
  2. Sequelize - ORM za MySQL

Za razvoj koji se odnosi na Javu postoji puno ORM-ova poput Hibernate, JPA (Java Persistence API) i Java objektno orijentiranog upita.

Odlučio sam graditi s JPA-om koji se tradicionalno koristi u Java aplikacijama.

Bilo je vrlo zanimljivo i trebalo mi je otprilike tjedan dana da završim jer sam usput morao naučiti Spring Boot (Puno je napomena " @ " i druge zanimljive stvari), JPA i Hibernate.

Svu ovu magiju uglavnom čine napomene ( simbol " @ ") korištene u Spring Boot-u.

Stvaranje projekta Spring Boot Maven

Stvorimo aplikaciju Spring Boot Maven Project pomoću ove veze.

" Maven " je alat za upravljanje projektima koji se koristi za upravljanje upravljanjem ovisnostima. To je poput Node Package Managera ( NPM ) u JS razvojnom okruženju.

Imamo package.json u NodeJS-u za upravljanje ovisnostima i pom.xml u Spring Boot-u za upravljanje ovisnostima.

U Grupu napišite kako god želite ime. Obično se naziv domene organizacije piše zdesna nalijevo.

Na primjer, ime naše domene je www.javaAPI.com, tako da naziv grupe može biti com.javaAPI.www

Zatim u Artifact unesite naziv mape koju želite .

S desne strane dodajte sljedeće ovisnosti:

  1. WEB - Za korištenje ovisnosti Springa (stariji okvir Spring Boot-a koji se koristi za razvoj web aplikacija)
  2. JPA - Java postojanost API
  3. MYSQL

Zatim kliknite "Generiraj projekt". Pronaći ćete rar datoteku - izvucite je. Zatim otvorite tu mapu u svom omiljenom IDE-u.

Kliknite com.rest.API i pronaći ćete datoteku ApiApplication.java kako slijedi:

package com.rest.API; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ApiApplication { public static void main(String[] args) { SpringApplication.run(ApiApplication.class, args); } }

Ovaj je kod dovoljan za pokretanje vašeg poslužitelja. Obično se proljetna čizma pokreće na localhost: 8080 .

Upišite svoj terminal na sljedeći način:

mvn spring-boot: trčanje

Pogledajte svoj localhost koji radi u web pregledniku na portu 8080. Izgleda prazno jer još nismo ništa učinili.

Istražimo datoteke i njihove oznake

Ako pogledate datoteku pom.xml, mogli biste primijetiti da će ovisnosti koje ste unijeli prilikom stvaranja aplikacije u Spring Initialize poput MySQL, JPA i Web biti unutar cy> oznaka.

Original text


Ovisnosti o pokretaču i ispitivaču jezgra su za stvaranje aplikacije Spring Boot koja će poslužiti na poslužitelju.

Idemo sada na APIApplication.java koja je glavna datoteka.

package com.rest.API; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ApiApplication { public static void main(String[] args) { SpringApplication.run(ApiApplication.class, args); } }

Ovdje se naziv paketa nalazi u prvom retku koda. Upotrebom tog naziva paketa možete uvesti bilo koju klasu, metodu ili primjerke u drugu datoteku paketa.

Nakon toga, dva modula se uvoze iz paketa "org.springframework.boot".

  1. SpringApplication
  2. SpringBootApplication

Budući da je Spring boot najnoviji okvir za razvoj aplikacija Springa, potrebni su mu paketi Spring Application kao i njegovi specifični paketi.

Nakon toga koristi se @SpringBootApplication Annotation. Ova se napomena sastoji od bilješke koja se koristi u proljeće:

  1. @Component - kaže kompajleru da je sljedeća klasa komponenta koja treba biti uključena prilikom sastavljanja cijele aplikacije.
  2. @ComponentScan - Ovaj skenira pakete koje ćemo koristiti u sljedećoj Java klasi.
  3. @EnableAutoConfiguration - omogućuje mehanizmu autokonfiguracije Spring Boota za uvoz važnih modula za pokretanje Spring Boota .

To su napomene koje se koriste za pokretanje aplikacije Spring Boot koja se izvodi na poslužitelju.

Evo članka koji sam napisao o Bilješkama i njihovoj upotrebi u Javi.

Stvorimo Model za naše podatke

Stvorimo klasu Model za spremanje, dohvaćanje, ažuriranje i brisanje detalja o knjizi.

Za to moram stvoriti novi paket nazvan model i unutar tog kreiranja klase Book.java da stavim svoj kôd.

package com.rest.API.model; import javax.persistence.*; import javax.validation.constraints.NotBlank; @Entity @Table(name = "books") public class Book { @Id @GeneratedValue private Long id; @NotBlank private String book_name; @NotBlank private String author_name; @NotBlank private String isbn; public Book(){ super(); } public Book(Long id, String book_name, String author_name, String isbn) { super(); this.id = id; this.book_name = book_name; this.author_name = author_name; this.isbn=isbn; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getBook_name() { return book_name; } public void setBook_name(String book_name) { this.book_name = book_name; } public String getAuthor_name() { return author_name; } public void setAuthor_name(String author_name) { this.author_name = author_name; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } }

Ovdje koristim JPA (Java Persistence API) koji je zbirka klasa i metoda za kontinuirano spremanje podataka u bazu podataka.

@Entity - koristi se za označavanje da će ova klasa biti Entitet u bazi podataka.

@Table - koja uzima neke vrijednosti poput imena kojemu ćete dati naziv tablice

@Id — denotes that the id is the primary key / identifying key for this table

@NotBlank — is used to say that these attributes should not be blank.

Other than that there is an empty constructor which has a super method to satisfy the JPA customs. Getter and setter methods are usually in a POJO class (Plain old Java object).

Creating the Repository

Next, we are going to create a repository package to deal with database management in Java.

Create an Interface called BookRepository.java inside the repository package.

package com.rest.API.repository; import com.rest.API.model.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BookRepository extends JpaRepository { }

I have imported the JpaRepository package to use that repository in the BookRepository interface by connecting my most recently coded Book model to do CRUD operations.

There are already built-in methods in those repositories to do CRUD operations.

Eg:

.findAll() - to get All datas .save() - to save the got Data .delete() - to delete the data

Inside the tag we are taking the Model name we are going to use and the Primary key’s datatype.

@Repository: Annotation used to Indicate the DAO (Data Access Object) component in the persistence layer.

It tells the compiler that the interface is going to use the Repository to do database activities.

Creating Controller and Exception Handling

Create a new package called controller, andinside that create a BookController.java file which contains the endpoints.

package com.rest.API.controller; import com.rest.API.exception.BookNotFoundException; import com.rest.API.model.Book; import com.rest.API.repository.BookRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.http.ResponseEntity; import javax.validation.Valid; import java.util.List; @RestController public class BookController { @Autowired BookRepository bookRepository; // Get All Notes @GetMapping("/books") public List getAllNotes() { return bookRepository.findAll(); } // Create a new Note @PostMapping("/books") public Book createNote(@Valid @RequestBody Book book) { return bookRepository.save(book); } // Get a Single Note @GetMapping("/books/{id}") public Book getNoteById(@PathVariable(value = "id") Long bookId) throws BookNotFoundException { return bookRepository.findById(bookId) .orElseThrow(() -> new BookNotFoundException(bookId)); } // Update a Note @PutMapping("/books/{id}") public Book updateNote(@PathVariable(value = "id") Long bookId, @Valid @RequestBody Book bookDetails) throws BookNotFoundException { Book book = bookRepository.findById(bookId) .orElseThrow(() -> new BookNotFoundException(bookId)); book.setBook_name(bookDetails.getBook_name()); book.setAuthor_name(bookDetails.getAuthor_name()); book.setIsbn(bookDetails.getIsbn()); Book updatedBook = bookRepository.save(book); return updatedBook; } // Delete a Note @DeleteMapping("/books/{id}") public ResponseEntity deleteBook(@PathVariable(value = "id") Long bookId) throws BookNotFoundException { Book book = bookRepository.findById(bookId) .orElseThrow(() -> new BookNotFoundException(bookId)); bookRepository.delete(book); return ResponseEntity.ok().build(); } }

The first imported package is for the Book Not Found exception (for which we are going to create a file in a bit).

Explanation of Annotations we used here:

  1. RestController: This annotation is used to denote every method in the annotated class as Domain Object.

So what is Domain Object…?

It simply says that Domain Object == Business Object.

They are usually represented by entities and value objects related to the endpoint we are giving to get the data from the database.

2. Autowired: This annotation is used to wire the bean classes automatically.

For that, you need to know about “What is a bean Class..?

Basically, a Java Bean Class is a simple class which encapsulates many objects into it.

This is an article I wrote on Java Bean Classes.

The following are the Mapping Annotations for the endpoints to perform CRUD Operations.

3. GetMapping: This is an interface which contains the path of the endpoint to perform a Get method. This GetMapping interface uses the RequestMapping interface which can have the “path, value, params, headers” method to perform the Get method in earlier Spring versions.

Now it’s simplified by using GetMapping.

4. PostMapping: This is an interface which contains the path of the endpoint to perform the Post method.

5. PutMapping: This is an interface which contains the path of the endpoint to perform the Put method to Update.

6. DeleteMapping: This is an interface which contains the path of the endpoint to perform the Delete method.

In the final lines, you probably noticed the “ResponseEntity” keyword.

What is that…??

It’s a Java class which inherits HttpEntity class to manipulate the HTTP Responses. Whether the request of the connection is “OK” or if there are any problems, throw an exception from the HttpEntity class.

orElseThrow(): This is a method found in the Optional class in Java8 which was introduced to handle Exceptions. The optional class provides various utility methods to check the presence or absence of an object, which helps to deal with NullPointerException.

orElseThrow is a method that Returns value if present, otherwise invokes an exception.

Creating a NotFoundException if there is no such book_id

As orElseThrow method throws a NotFound Exception. The following is the Exception Handling part. Create a BookNotFoundException.java file inside exception package.

package com.rest.API.exception; public class BookNotFoundException extends Exception { private long book_id; public BookNotFoundException(long book_id) { super(String.format("Book is not found with id : '%s'", book_id)); } }

The created class extends the Superclass of Exception. In the constructor, I’m passing the book_id & prints the exception.

So, that’s it…

We have finished the REST API part. Now you can build the app (which was explained in Part 1) and do some Testings with Postman.

Connecting with MySql Database

Inside the application.properties of your resources folder, add the following:

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url = jdbc:mysql://localhost:3306/library spring.datasource.username = root //normally put your MySQL username spring.datasource.password = YOUR_MYSQL_PASSWORD ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto = update

That’s it.

We have built a basic REST API in Spring Boot. Congrats!

If anything is wrong or need to be corrected, please let me know in the comments section.

Get in touch with me on twitter.

Happy Coding!