Proyecto SpringBoot:
CLASE RESERVATION
public class Reservation {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
@ManyToOne(fetch = [Link])
@JoinColumn(name = "user_id")
private User user;
@Column(nullable = false)
private LocalDateTime date;
@Column(nullable = false)
private int duration;
// Constructores, getters y setters
}
CLASE USUARIOS
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@OneToMany(mappedBy = "user", cascade = [Link], fetch =
[Link])
private List<Reservation> reservations = new ArrayList<>();
// Constructores, getters y setters
}
En esta clase, utilizamos las anotaciones de JPA (@Entity, @Table, @Id, @GeneratedValue,
@Column) para indicar que se trata de una entidad persistente en la base de datos, y para
mapear los atributos de la clase con las columnas correspondientes en la tabla "reservations".
@Repository
public interface ReservationRepository extends
JpaRepository<Reservation, Long> {
List<Reservation> findByEmail(String email);
En esta interfaz, utilizamos la anotación @Repository para indicar que
se trata de un repositorio de Spring Data JPA, y extendemos de la
interfaz JpaRepository, que proporciona métodos predefinidos para
realizar operaciones básicas de persistencia (como save, findById,
findAll, etc.). Además, definimos un método personalizado findByEmail,
que buscará reservas por correo electrónico.
CLASE RESERVATIONCONTROLLER
@RestController
@RequestMapping("/reservations")
public class ReservationController {
@Autowired
private ReservationRepository reservationRepository;
@PostMapping("/")
public Reservation createReservation(@RequestBody Reservation
reservation) {
return [Link](reservation);
}
@GetMapping("/")
public List<Reservation> getAllReservations() {
return [Link]();
}
@GetMapping("/{id}")
public ResponseEntity<Reservation>
getReservationById(@PathVariable(value = "id") Long reservationId)
throws ResourceNotFoundException {
Reservation reservation =
[Link](reservationId)
.orElseThrow(() -> new
ResourceNotFoundException("Reservation not found for this id :: " +
reservationId));
return [Link]().body(reservation);
}
@PutMapping("/{id}")
public ResponseEntity<Reservation>
updateReservation(@PathVariable(value = "id") Long reservationId,
@RequestBody Reservation reservationDetails) throws
ResourceNotFoundException {
Reservation reservation =
[Link](reservationId)
.orElseThrow(() -> new
ResourceNotFoundException("Reservation not found for this id :: " +
reservationId));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
final Reservation updatedReservation =
[Link](reservation);
return [Link](updatedReservation);
}
@DeleteMapping("/{id}")
public Map<String, Boolean> deleteReservation(@PathVariable(value
= "id") Long reservationId)
throws ResourceNotFoundException {
Reservation reservation =
[Link](reservationId)
.orElseThrow(() -> new
ResourceNotFoundException("Reservation not found for this id :: " +
reservationId));
[Link](reservation);
Map<String, Boolean> response = new HashMap<>();
[Link]("deleted", [Link]);
return response;
}
import React, { useState } from 'react';
import { StyleSheet, Text, TextInput, TouchableOpacity, View } from
'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
const LoginScreen = () => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigation = useNavigation();
const handleLogin = async () => {
// Aquí podrías hacer una petición al servidor de Spring Boot para
autenticar al usuario
// y obtener el token de autenticación. Por simplicidad, aquí
simplemente almacenamos
// el correo electrónico del usuario en AsyncStorage y navegamos a
la pantalla principal.
await [Link]('email', email);
[Link]('Main');
};
return (
<View style={[Link]}>
<Text style={[Link]}>Iniciar sesión</Text>
<TextInput
style={[Link]}
placeholder="Correo electrónico"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
keyboardType="email-address"
/>
<TextInput
style={[Link]}
placeholder="Contraseña"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<TouchableOpacity style={[Link]} onPress={handleLogin}>
<Text style={[Link]}>Iniciar sesión</Text>
</TouchableOpacity>
<TouchableOpacity
style={[Link]}
onPress={() => [Link]('Register')}
>
<Text style={[Link]}>¿No tienes una cuenta?
Regístrate aquí.</Text>
</TouchableOpacity>
</View>
);
};
const RegisterScreen = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigation = useNavigation();
const handleRegister = async () => {
// Aquí podrías hacer una petición al servidor de Spring Boot para
crear un nuevo usuario
// y obtener el token de autenticación. Por simplicidad, aquí
simplemente almacenamos
// el correo electrónico del usuario en AsyncStorage y navegamos a
la pantalla principal.
await [Link]('email', email);
[Link]('Main');
};
return (
<View style={[Link]}>
<Text style={[Link]}>Regístrate</Text>
<TextInput
style={[Link]}
placeholder="Nombre completo"
value={name}
onChangeText={setName}
/>
<TextInput
style={[Link]}
placeholder="Correo electrónico"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
keyboardType="email-address"
/>
<TextInput
style={[Link]}
placeholder="Contraseña"
value={password}
onChangeText={setPassword}
secureTextEntry
/>
<TouchableOpacity style={[Link]}
onPress={handleRegister}>
<Text style={[Link]}>Regístrate</Text>
</TouchableOpacity>
<TouchableOpacity
style={[Link]}
onPress={() => [Link]('Login')}
>
<Text style={[Link]}>¿Ya tienes una cuenta? Inicia
sesión aquí.</Text>
</TouchableOpacity>
</View>
);
};
const MainScreen = () => {
const [email, setEmail] = useState('');
const navigation