Contenido
Descripción
Para publicar y consumir algunos métodos del API REST vamos a crear y conectarnos a una Base de Datos MySQL.
Crear la Base de Datos
Con el siguiente script podemos crear la Base de Datos en MySQL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
-- MySQL dump 10.13 Distrib 5.7.19, for Linux (x86_64) -- -- Host: localhost Database: Pruebas -- ------------------------------------------------------ -- Server version 5.7.19-0ubuntu0.16.04.1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `Persona` -- DROP TABLE IF EXISTS `persona`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `persona` ( `idPersona` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(200) NOT NULL, `edad` int(11) NOT NULL, `sexo` char(1) NOT NULL, PRIMARY KEY (`idPersona`), UNIQUE KEY `idPersona_UNIQUE` (`idPersona`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Persona` -- /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2017-08-29 12:27:04 |
Agregar dependencias
Tomamos el proyecto http://arieloliva.com/api-rest-en-spring/.
En el archivo pom.xml agregamos las dependencias necesarias:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> |
Crear archivo Application.properties
En la ruta src/main/resources del proyecto creamos el archivo application.properties. Agregamos los siguientes parámetros de la conexión a la Base de Datos.
1 2 3 4 5 |
spring.jpa.show-sql = true spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/Pruebas spring.datasource.username=root spring.datasource.password=root |
Crear entity
Un entity es el modelado de una tabla. Nuestra tabla se llama Persona y tiene los campos:
Nombre | Tipo | Tamaño | Null | AutoIncrementar |
idPersona | int | 11 | no | si |
nombre | varchar | 200 | no | no |
edad | int | 11 | no | no |
sexo | char | 1 | no | no |
Con estos datos podemos crear la Clase que modela la tabla.
- Crear Clase en el paquete hello con nombre Persona
- variables privadas idPersona, nombre, edad y sexo con sus respectivos set y get
- Anotación @Entity en la Clase para indicar que es un entity.
- Anotación @Id y @GeneratedValue(strategy=GenerationType.IDENTITY) en la variable idPersona. para indicar que es el identificador único y se auto genera.
El resultado final es:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package hello; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Persona implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int idPersona; private int edad; private String nombre; private String sexo; public Persona() { } public int getIdPersona() { return this.idPersona; } public void setIdPersona(int idPersona) { this.idPersona = idPersona; } public int getEdad() { return this.edad; } public void setEdad(int edad) { this.edad = edad; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getSexo() { return this.sexo; } public void setSexo(String sexo) { this.sexo = sexo; } } |
Crear repositorio
Un repositorio es una interface con los métodos necesarios para acceso a la Base de Datos.
- Crear Interface en el paquete hello con nombre PersonaRepository
- Extendemos de CrudRepository<Persona, Long>. Crud (Create, Read, Update, Delete). Proporciona todos los métodos para Crear, Leer, Actualizar y Borrar los datos de la tabla.
El resultado final es:
1 2 3 4 5 6 7 |
package hello; import org.springframework.data.repository.CrudRepository; public interface PersonaRepository extends CrudRepository<Persona, Long>{ } |
Crear controlador
- Crear Clase en el paquete hello con nombre PersonaController
- Anotaciones @RestController y @RequestMapping(path=»/persona») en la Clase. Para indicar que que es una API REST y la base del mapeo es /persona.
- Variable private PersonaRepository personaRepository con anotación @Autowired la cual obtiene el llamado a PersonaRepository.
- Método public Iterable<Persona> getPersona() con la anotación @RequestMapping(«/all») para obtener todos los datos de la tabla persona con el mapeo all.
El resultado final es:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(path="/persona") public class PersonaController { @Autowired private PersonaRepository personaRepository; @RequestMapping("/all") public Iterable<Persona> getPersona() { return personaRepository.findAll(); } } |
Ejecutar aplicación
Después de ejecutar la aplicación el resultado obtenido es:
Otros
Descargar proyecto
Se puede descargar el proyecto completo de https://github.com/arielolivagh/gs-rest-service-complete/tree/v1.0