Home > OS >  Get logged in user ID filled as a foreign key when user makes a reservation
Get logged in user ID filled as a foreign key when user makes a reservation

Time:02-03

I am very new to Java and Spring Boot. I am trying to complete this web application assignment about a ticket reservation system.

I have linked the Reservation and User Database Table by @ManyToOne

Reservation

package com.codejava.reservation;

import com.codejava.user.User;
import jakarta.persistence.*;

@Entity
@Table(name="reservation")
public class Reservation {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column (nullable = false)
    private String ticket_firstname;

    @Column (nullable = false)
    private String ticket_lastname;

    @Column (nullable = false)
    private String from_station;

    @Column (nullable = false)
    private String to_station;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name ="user_id", referencedColumnName = "id", insertable = true, updatable = false)
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public int getId() {
        return id;
    }

    public void setId(int ticket_id) {
        this.id = id;
    }

    public String getTicket_firstname() {
        return ticket_firstname;
    }

    public void setTicket_firstname(String ticket_firstname) {
        this.ticket_firstname = ticket_firstname;
    }

    public String getTicket_lastname() {
        return ticket_lastname;
    }

    public void setTicket_lastname(String ticket_lastname) {
        this.ticket_lastname = ticket_lastname;
    }

    public String getFrom_station() {
        return from_station;
    }

    public void setFrom_station(String from_station) {
        this.from_station = from_station;
    }

    public String getTo_station() {
        return to_station;
    }

    public void setTo_station(String to_station) {
        this.to_station = to_station;
    }
}

User

package com.codejava.user;

import com.codejava.reservation.Reservation;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false, length=45)
    private String firstName;

    @Column(nullable = false, length=45)
    private String lastName;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private Set<Reservation> reservationList= new HashSet<>();

    public Set<Reservation> getReservationList() {
        return reservationList;
    }

    public void setReservationList(Set<Reservation> reservationList) {
        this.reservationList = reservationList;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

I want the user_id field in the Reservation table automatically filled with the current logged-in User-ID when the user make a new reservation.

The user_id field is not filled when the logged-in user makes a new reservation

ReservationController

package com.codejava.reservation;

import com.codejava.user.CustomUserDetails;
import com.codejava.user.User;
import com.codejava.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Service
@Controller
public class ReservationController {

    @Autowired
    private ReservationService reservationService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ReservationRepository reservationRepository;

    public ReservationController() {
    }

    @GetMapping ("/make_reservation")
    public String makeReservation(Model model){
        model.addAttribute("user", new User());
        model.addAttribute("reservation", new Reservation());
        return "make_reservation";
    }

    @PostMapping("/make_reservation")
    public String saveReservation(Reservation reservation) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CustomUserDetails user = (CustomUserDetails)principal;

        reservationRepository.save(reservation);

        return "index";
    }

ReservationService

package com.codejava.reservation;

import com.codejava.user.User;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class ReservationService {

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @Autowired
    private ReservationRepository reservationRepo;
}

I am very new and the requirement for the project is kinda ridiculously hard for beginners. I have been researching very hard but I still cannot figure it out. I really appreciate it if you can help me and give me some clear instructions.

CodePudding user response:

DB mapping is correct. In reservation table you have user_id column but in java persistance you have entire User object(which internally maps id of user to user_id of reservation)
Your code snippet does not shows how logged user data is managed, I will suggest after login pass User object to GET /make_reservation request

 model.addAttribute("user", LOGGED_IN_USER);

and before saving reservation object set user to it.

If passing entire user object is not possible pass id of user to model on reservation post method get user by findById and then set it to reservation object and save reservation entity.

CodePudding user response:

You need to set the user in the reservation object before saving it in reservationRepository.

Something like this:

    Optional<User> optionalUser = userRepository.findById(userId);
    Optional<Reservation> optionalReservation =reservationRepository.findById(reservationId);
    if (!optionalReservation.isEmpty() || !optionalUser.isEmpty()) {
         User user = optionalUser.get();
         Reservation reservation = optionalReservation.get();
         reservation.setUser(user); //You are missing this in your code
         reservationRepository.save(reservation);

This method should be in the reservationService and should be called by the reservationController. You should have always separate layer in your application, so you shouldn't call the repository directly in the controller. The right path of calls: Controller -> Service -> Repository

  • Related