Ejemplo Spring con SQL-Server
Ejemplo Spring con SQL-Server
Descarga el pluggin.
Puedes descargarlo en la siguiente dirección:
https://plugins.netbeans.apache.org/catalogue/?id=4
Instala el Pluggin.
Abre el NetBeans y dirijete a Tools -> Pluggings
En la ventana, ve a la pestaña, downloaded.
Haz click en el botón Add Plugins ...
Selecciona el pluggin descargado y sigue las instrucciones de instalación.
Inicia un nuevo proyecto.
En NetBeans crea un nuevo proyecto con Maven y Spring Boot Initializer ...
En la ventana de dependencias selecciona:
Configura el archivo application.properties:
Crea una clase modelo:
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package law.layers.models;
import lombok.Data;
/**
*
* @author mc_fe
*/
@Data
public class Persona {
public String Nombre, Ape1, Ape2, CURP;
public long Id;
public String toJson(){
String s = "{";
char comilla = 34;
s += comilla + "Nombre" + comilla + ":" + comilla + Nombre + comilla + ",";
s += comilla + "Ape1" + comilla + ":" + comilla + Ape1 + comilla + ",";
s += comilla + "Ape2" + comilla + ":" + comilla + Ape2 + comilla + ",";
s += comilla + "CURP" + comilla + ":" + comilla + CURP + comilla + ",";
s += comilla + "Id" + comilla + ":" + Id + "}";
return s;
}
}
Crea una clase Repository:
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package law.layers.repository;
import java.util.List;
import law.layers.models.Persona;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
*
* @author mc_fe
*/
@Repository
public class PersonaRepository implements ICrudRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int Add(Object o) {
int id = 0;
Persona item = (Persona)o;
String sql = "INSERT INTO Persona (Nombre, Ape1, Ape2, CURP) VALUES(?, ?, ?, ?)";
id = jdbcTemplate.update(sql, item.Nombre, item.Ape1, item.Ape2, item.CURP);
return id;
}
@Override
public String getAll() {
String sql = "SELECT * FROM Persona", json;
char comillas = 34;
//jdbcTemplate = new JdbcTemplate();
List<Persona> ls = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Persona.class));
json = "{" + comillas + "Personas" + comillas + ":[";
if (!ls.isEmpty()) {
for (Persona item : ls) {
json += item.toJson() + ",";
}
}
json = json.substring(0, json.length() - 1);
json += "]}";
return json;
}
@Override
public String getById(int id) {
String sql = "SELECT * FROM Persona WHERE Id = ? ", json;
try{
Persona item = jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(Persona.class), id);
if(item != null)
json = item.toJson();
else
json = "null";
}catch(DataAccessException e){
json = e.getMessage();
}
return json;
}
@Override
public int Update(Object o) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
@Override
public int Delete(int id) {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}
Crea la clase controller:
import com.google.gson.Gson;
import law.layers.models.Persona;
import law.layers.repository.PersonaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class LayersApplication {
public static void main(String[] args) {
SpringApplication.run(LayersApplication.class, args);
}
@RestController
public class PersonaMS {
@Autowired
private PersonaRepository persona;
@GetMapping("/personas/get")
public String Get() {
return persona.getAll();
}
@GetMapping("/personas/get/{id}")
public String GetByID(@PathVariable("id") int id) {
return persona.getById(id);
}
@PutMapping("/personas/insert")
public int Insert(@RequestBody Persona item) {
return persona.Add(item);
}
}
}
Crea una tabla en SQL Server.
CREATE TABLE Persona(
Id int IDENTITY(1,1) NOT NULL,
Nombre varchar(50) NOT NULL,
Ape1 varchar(50) NOT NULL,
Ape2 varchar(50) NULL,
CURP char(20) NOT NULL,
CONSTRAINT PK_Persona PRIMARY KEY (Id)
)
Prueba que funcione tu App.
Lo puedes probar con el navegador si el GetMapping o desde una app si el método es PutMapping.
Prueba PutMapping:
El comando es:
curl -X PUT -H "Content-Type: application/json" -d '{"Nombre":"LUPE","Ape1":"PECH","Ape2":"UC","CURP":"FASFHFA","Id":7}' http://localhost:8080/personas/insert





Comentarios
Publicar un comentario