0% found this document useful (0 votes)
16 views9 pages

Glab S14 Jbeeck 2024 1

xavdfvcadqwefgdf

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views9 pages

Glab S14 Jbeeck 2024 1

xavdfvcadqwefgdf

Uploaded by

aa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Desarrollo de Aplicaciones Web

LABORATORIO Nº 14
JPA en Spring Boot

Alumno(s): Nota

Grupo: Ciclo: IV

Requiere No
Excelente Bueno Puntaje
Criterio de Evaluación mejora acept.
(4pts) (3pts) Logrado
(2pts) (0pts)
Instala, configura la arquitectura necesaria
para la puesta en marcha de la aplicación de
software.
Crea el MVC propuesto.
La información se almacena en la BD.
Logra conectarse a los endpoints propuestos.
Se comunican efectivamente de manera oral,
escrita y gráfica.
TEMA: MVC persistente y JPA en el Framework Spring Boot
OBJETIVOS
● Crear un proyecto con conexión a una base de datos relacional.

REQUERIMIENTOS
● Java SDK
● MySQL.
Nro. xxx
Página 2/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

MARCO TEÓRICO

PROCEDIMIENTO
(** El laboratorio se ha diseñado para ser desarrollado en grupos de 2 o 3 personas**)

1. Crear un objeto Student usando JPA.


- Dependencias: Spring Web, Spring Data JPA, MySQL Driver.
- Crear las carpetas necesarias para el proyecto.

Añadir la Configuración de MySQL en el archivo application.properties.


spring.datasource.url=jdbc:mysql://localhost:3306/lab14
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Creación del Modelo Student.

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Table(name = "students")
public class Student {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;

// Getters and setters


public Long getId() {
return id;
}
Nro. xxx
Página 3/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

public void setId(Long id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

Creación del Repositorio, la interfaz para las operaciones CRUD en la entidad Student.

package com.example.demo.repository;

import com.example.demo.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

// Find students by name


List<Student> findByName(String name);

// Find students by age range


List<Student> findByAgeBetween(int minAge, int maxAge);

// Find students whose name starts with a specific prefix


@Query("SELECT s FROM Student s WHERE s.name LIKE ?1%")
List<Student> findByPrefix(String prefix);
}
Nro. xxx
Página 4/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

Creación del Servicio Student. La clase contiene la lógica de negocios para las operaciones de Student.

package com.example.demo.service;

import com.example.demo.model.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

@Autowired
private StudentRepository studentRepository;

public Student createStudent(Student student) {


return studentRepository.save(student);
}

public List<Student> getAllStudents() {


return studentRepository.findAll();
}

public Optional<Student> getStudentById(Long id) {


return studentRepository.findById(id);
}

public Student updateStudent(Long id, Student studentDetails) {


Student student = studentRepository.findById(id).orElseThrow();
student.setName(studentDetails.getName());
student.setAge(studentDetails.getAge());
return studentRepository.save(student);
}

public void deleteStudent(Long id) {


studentRepository.deleteById(id);
}

// Custom method to find students by name


Nro. xxx
Página 5/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

public List<Student> getStudentsByName(String name) {


return studentRepository.findByName(name);
}

// Custom method to find students by age range


public List<Student> getStudentsByAgeRange(int minAge, int maxAge) {
return studentRepository.findByAgeBetween(minAge, maxAge);
}

// Custom method to find students whose name starts with a specific prefix
public List<Student> getStudentsByPrefix(String prefix) {
return studentRepository.findByPrefix(prefix);
}

Creación del Controlador Student.

package com.example.demo.controller;

import com.example.demo.model.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/students")
public class StudentController {

@Autowired
private StudentService studentService;

@PostMapping
public Student createStudent(@RequestBody Student student) {
return studentService.createStudent(student);
}

@GetMapping
public List<Student> getAllStudents() {
Nro. xxx
Página 6/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

return studentService.getAllStudents();
}

@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable Long id) {
Optional<Student> student = studentService.getStudentById(id);
return student.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
}

@PutMapping("/{id}")
public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student
studentDetails) {
Student updatedStudent = studentService.updateStudent(id, studentDetails);
return ResponseEntity.ok(updatedStudent);
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
studentService.deleteStudent(id);
return ResponseEntity.noContent().build();
}

// Custom endpoint to find students by name


@GetMapping("/byname/{name}")
public List<Student> getStudentsByName(@PathVariable String name) {
return studentService.getStudentsByName(name);
}

// Custom endpoint to find students by age range


@GetMapping("/byage/{minAge}/{maxAge}")
public List<Student> getStudentsByAgeRange(@PathVariable int minAge, @PathVariable int
maxAge) {
return studentService.getStudentsByAgeRange(minAge, maxAge);
}

// Custom endpoint to find students whose name starts with a specific prefix
@GetMapping("/byprefix/{prefix}")
public List<Student> getStudentsByPrefix(@PathVariable String prefix) {
return studentService.getStudentsByPrefix(prefix);
}

Llenar los datos en la BD.


Nro. xxx
Página 7/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

INSERT INTO students (name, age) VALUES


('John Doe', 20),
('Alice Smith', 22),
('Bob Johnson', 21),
('Emma Watson', 23),
('Michael Brown', 22);

Utilice Postman o el navegador para ejecutar los siguientes endpoints.

Create a Student: POST /api/students with JSON body


Get All Students: GET /api/students
Get Student by ID: GET /api/students/{id}
Update Student: PUT /api/students/{id} with JSON body
Delete Student: DELETE /api/students/{id}

Find Students by Name: GET /api/students/byname/{name}


Find Students by Age Range: GET /api/students/byage/{minAge}/{maxAge}
Find Students by Name Prefix: GET /api/students/byprefix/{prefix}

GET /api/students/byname/{name}
GET /api/students/byname/John20Doe%
http://localhost:8080/api/students/byname/John%20Doe

GET /api/students/byage/{minAge}/{maxAge}
GET /api/students/byage/20/25
http://localhost:8080/api/students/byage/20/25

GET /api/students/byprefix/{prefix}
GET /api/students/byprefix/John
http://localhost:8080/api/students/byprefix/John
Nro. xxx
Página 8/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

2. Cree un objeto usando JPA y pruebe los endpoints (mínimo tres) que ustedes vean necesario.
Nro. xxx
Página 9/9
DISEÑO Y DESARROLLO DE SOFTWARE Laboratorio Nro. 01
CURSO: Desarrollo de Aplicaciones Web

Conclusiones:
Indicar las conclusiones que llegó después de los temas tratados de manera práctica en este laboratorio.

You might also like