- Obtener vínculo
- X
- Correo electrónico
- Otras apps
Bienvenido a mi blog!
En esta entrada quiero compartirte un ejemplo básico de una REST Api o RESTFul API como comúnmente se le conoce.
Tecnologías usadas:
- SpringBoot
- JPA
- MySQL
- Gradle
Comúnmente cuando se habla de un microservicio dentro de la programación, suele haber muchas formas de entenderse, ya que por facilidad o habilidad dentro del equipo de desarrollo se van acuñando nuevos términos para referirse a un mismo concepto. Tal es el caso del microservicio, que también se le puede llamar end-point en términos mucho mas específicos y técnicos.
En esta ocasión he preparado un Microservicio que obtiene los registros de una tabla de base de datos MySQL usando Java con el Framework SpringBoot. Es algo básico para empezar en este mundo de los microservicios.
La estructura general del proyecto se ve así con Gradle usando Spring Tool Suite 4 como IDE
La estructura del código src
Un proyecto de SpringBoot tiene que tenes una estructura que se entienda, por ello he estructurado el código en paquetes, controllers, modelos, repositorios y servicios. Comúnmente también se agrega el dto y el dao, pero en este caso así es suficiente.
La parte de dependencias o librerias de nuestro proyecto las administra Gradle y se ve así
La configuración de la base de datos la tendremos en el archivo application.properties
en el paquete com.game.start.model se encuentra la clase Libro.java que es el modelo que representa la base de datos en MySql
Ahora tenemos el repositorio que por default SpringBoot trae implementados automaticamente, esto nos permitirá ahorrarnos código, simplemente tenemos que extender de JpaReposiotory para poder usar sus métodos
Tendremos un servicio que irá hacia el repositorio para ejecutar el metodo necesario, en este caso el que nos hace un select * a la tabla correspondiente
La parte mas importante es el controller ya que en él se define el metodo que se expondra al servicio cliente para que lo consuma. En este caso estamos declarando que este microservicio se invocará o consumirá con el metodo GET.
Por último tendremos el main que levantara el microservicio
Para ejecutar nuestro Microservicio podemos usar nuestro IDE desde el botón o bien ejecutarlo desde la terminal con el comando gradle bootRun
Podemos invocar nuestro microservicio desde otro microservicio, desde el front de alguna aplicación, en este caso lo haremos con Postman para testear nuestra REST API
Esto sería todo de mi parte. Si les surge alguna duda pueden contactarme a mi correo o ami facebook.
Les dejo el link del proyecto
Link
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
plugins { | |
id 'org.springframework.boot' version '2.4.2' | |
id 'io.spring.dependency-management' version '1.0.11.RELEASE' | |
id 'java' | |
} | |
group = 'com.game' | |
version = '0.0.1-SNAPSHOT' | |
sourceCompatibility = '1.8' | |
configurations { | |
compileOnly { | |
extendsFrom annotationProcessor | |
} | |
} | |
repositories { | |
mavenCentral() | |
} | |
dependencies { | |
implementation 'org.springframework.boot:spring-boot-starter-data-jpa', | |
'org.springframework.boot:spring-boot-starter-web' | |
compileOnly 'org.projectlombok:lombok' | |
runtimeOnly 'mysql:mysql-connector-java' | |
annotationProcessor 'org.projectlombok:lombok' | |
testImplementation 'org.springframework.boot:spring-boot-starter-test' | |
} | |
test { | |
useJUnitPlatform() | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
spring.jpa.hibernate.ddl-auto=none | |
spring.datasource.url=jdbc:mysql://localhost:3306/biblioteca | |
spring.datasource.username=ivanovich | |
spring.datasource.password= | |
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.game.start.model; | |
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 = "libro") | |
public class Libro { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long idlibro; | |
@Column(name = "titulo") | |
private String titulo; | |
@Column(name = "autor") | |
private String autor; | |
@Column(name = "n_paginas") | |
private int n_paginas; | |
@Column(name = "editorial") | |
private String editorial; | |
@Column(name = "img") | |
private String img; | |
@Column(name = "categoria_idcategoria") | |
private int categoria_idcategoria; | |
@Column(name = "pdf") | |
private String pdf; | |
public Long getIdlibro() { | |
return idlibro; | |
} | |
public void setIdlibro(Long idlibro) { | |
this.idlibro = idlibro; | |
} | |
public String getTitulo() { | |
return titulo; | |
} | |
public void setTitulo(String titulo) { | |
this.titulo = titulo; | |
} | |
public String getAutor() { | |
return autor; | |
} | |
public void setAutor(String autor) { | |
this.autor = autor; | |
} | |
public int getN_paginas() { | |
return n_paginas; | |
} | |
public void setN_paginas(int n_paginas) { | |
this.n_paginas = n_paginas; | |
} | |
public String getEditorial() { | |
return editorial; | |
} | |
public void setEditorial(String editorial) { | |
this.editorial = editorial; | |
} | |
public String getImg() { | |
return img; | |
} | |
public void setImg(String img) { | |
this.img = img; | |
} | |
public int getCategoria_idcategoria() { | |
return categoria_idcategoria; | |
} | |
public void setCategoria_idcategoria(int categoria_idcategoria) { | |
this.categoria_idcategoria = categoria_idcategoria; | |
} | |
public String getPdf() { | |
return pdf; | |
} | |
public void setPdf(String pdf) { | |
this.pdf = pdf; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.game.start.respository; | |
import org.springframework.data.jpa.repository.JpaRepository; | |
import org.springframework.stereotype.Repository; | |
import com.game.start.model.Libro; | |
@Repository | |
public interface BookRepository extends JpaRepository<Libro, Long>{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.game.start.service; | |
import java.util.List; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.stereotype.Service; | |
import org.springframework.transaction.annotation.Transactional; | |
import com.game.start.model.Libro; | |
import com.game.start.respository.BookRepository; | |
@Service | |
@Transactional | |
public class BookService { | |
@Autowired | |
private BookRepository repository; | |
public List<Libro> listAll(){ | |
return repository.findAll(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.game.start.controller; | |
import java.util.List; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.ResponseEntity; | |
import org.springframework.stereotype.Controller; | |
import org.springframework.web.bind.annotation.GetMapping; | |
import com.game.start.model.Libro; | |
import com.game.start.service.BookService; | |
@Controller | |
public class BookController { | |
@Autowired | |
private BookService service; | |
@GetMapping("/") | |
public ResponseEntity<Object> listBooks(){ | |
List<Libro> libros = service.listAll(); | |
return new ResponseEntity<>(libros, HttpStatus.ACCEPTED); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.game.start; | |
import org.springframework.boot.SpringApplication; | |
import org.springframework.boot.autoconfigure.SpringBootApplication; | |
@SpringBootApplication | |
public class DemoApplication { | |
public static void main(String[] args) { | |
SpringApplication.run(DemoApplication.class, args); | |
} | |
} |
Link
- Obtener vínculo
- X
- Correo electrónico
- Otras apps
Comentarios
Publicar un comentario