CRUD con Spring Boot 4 + JPA + MySQL + Bootstrap 🚀
CRUD con Spring Boot 4 + JPA + MySQL + Bootstrap (Guía Completa)
Si estás aprendiendo Spring Boot o necesitas crear un sistema rápido tipo CRUD para una base de datos, este tutorial te guía paso a paso para construir una aplicación real usando:
✅ Spring Boot 4
✅ JPA (Hibernate)
✅ MySQL
✅ Thymeleaf
✅ Bootstrap
Trabajaremos con la tabla city de la base de datos world.
🧠 ¿Qué vamos a construir?
Un sistema web que permita:
📋 Listar ciudades
➕ Agregar nuevas
✏️ Editar registros
❌ Eliminar datos
🧱 1. Dependencias del proyecto
Agrega estas dependencias en tu archivo pom.xml:
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Vistas -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
</dependencies>
⚙️ 2. Configuración de base de datos
En application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/world
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.thymeleaf.cache=false
🧩 3. Crear la entidad City
Representa la tabla city en Java:
import jakarta.persistence.*;
@Entity
@Table(name = "city")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@Column(name = "CountryCode")
private String countryCode;
private String district;
private Integer population;
// getters y setters
}
🗂️ 4. Crear el repositorio
import org.springframework.data.jpa.repository.JpaRepository;
import com.ejemplo.demo.model.City;
public interface CityRepository extends JpaRepository<City, Integer> {
}
Esto te da automáticamente operaciones CRUD sin escribir SQL.
🧠 5. Controlador (lógica del sistema)
package com.ejemplo.demo.controller;
import com.ejemplo.demo.model.City;
import com.ejemplo.demo.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class CityController {
@Autowired
private CityRepository repo;
// LISTAR
@GetMapping("/")
public String listar(Model model) {
model.addAttribute("cities", repo.findAll());
return "index";
}
// FORM NUEVO
@GetMapping("/nuevo")
public String nuevo(Model model) {
model.addAttribute("city", new City());
return "form";
}
// GUARDAR
@PostMapping("/guardar")
public String guardar(@ModelAttribute City city) {
repo.save(city);
return "redirect:/";
}
// EDITAR
@GetMapping("/editar/{id}")
public String editar(@PathVariable Integer id, Model model) {
City city = repo.findById(id).orElse(null);
model.addAttribute("city", city);
return "form";
}
// ELIMINAR
@GetMapping("/eliminar/{id}")
public String eliminar(@PathVariable Integer id) {
repo.deleteById(id);
return "redirect:/";
}
}
🎨 6. Interfaz con Bootstrap
📄 Vista principal (index.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Ciudades</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
<h2>Lista de Ciudades</h2>
<a href="/nuevo" class="btn btn-primary mb-3">Nueva Ciudad</a>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>País</th>
<th>Distrito</th>
<th>Población</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<tr th:each="c : ${cities}">
<td th:text="${c.id}"></td>
<td th:text="${c.name}"></td>
<td th:text="${c.countryCode}"></td>
<td th:text="${c.district}"></td>
<td th:text="${c.population}"></td>
<td>
<a th:href="@{/editar/{id}(id=${c.id})}" class="btn btn-warning btn-sm">Editar</a>
<a th:href="@{/eliminar/{id}(id=${c.id})}" class="btn btn-danger btn-sm">Eliminar</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
📄 Formulario (form.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Formulario</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
<h2>Formulario Ciudad</h2>
<form th:action="@{/guardar}" th:object="${city}" method="post">
<input type="hidden" th:field="*{id}" />
<div class="mb-3">
<label>Nombre</label>
<input type="text" th:field="*{name}" class="form-control"/>
</div>
<div class="mb-3">
<label>País</label>
<input type="text" th:field="*{countryCode}" class="form-control"/>
</div>
<div class="mb-3">
<label>Distrito</label>
<input type="text" th:field="*{district}" class="form-control"/>
</div>
<div class="mb-3">
<label>Población</label>
<input type="number" th:field="*{population}" class="form-control"/>
</div>
<button class="btn btn-success">Guardar</button>
<a href="/" class="btn btn-secondary">Cancelar</a>
</form>
</body>
</html>
🧪 7. Resultado final
Con este proyecto tendrás:
✔ CRUD completo funcional
✔ Conexión a MySQL
✔ Interfaz web
✔ Código limpio y escalable
🔥 Conclusión
Spring Boot + JPA es una de las formas más rápidas y poderosas de crear aplicaciones empresariales en Java. Con muy poco código puedes tener un sistema completamente funcional.
.png)
Comentarios
Publicar un comentario