Home > database >  Insert users id to the patient in Spring Boot
Insert users id to the patient in Spring Boot

Time:05-23

I can't insert the id of the currently logged-in user while making the patient data. I want the user to be able to add his own patients, but the problem is that when I add a new patient, the column id_user is null

I tried lots of ways but couldn't add id_user to the patient. What do I miss?

This is my User Entity:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idUser;
    private String firstName;
    private String lastName;
    private String username;
    ...

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    @JoinTable(name = "users_roles",
            joinColumns = @JoinColumn(name = "id_user"),
            inverseJoinColumns = @JoinColumn(name = "id_role"))
    @JsonManagedReference
    private Set<Role> roles = new HashSet<>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private List<Patient> patients = new ArrayList<>();

    public void add(Patient patient) {
        if (patient != null) {
            if (patients == null) {
                patients = new ArrayList<>();
            }
        patients.add(patient);
        patient.setUser(this);
        }
    }

Patient Entity:

   @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_patient")
    private int idPatient;

    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
...

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;    
}

Controller

 @RequestMapping("/addPatient")
    public String addPatient(Model theModel, HttpServletRequest request) {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userD = (UserDetails) auth.getPrincipal();
        User u = userService.findByUsername(userD.getUsername());

        request.getSession().setAttribute("id_user", u.getIdUser());
//        int userId = user.getIdUser();
        int userId = (int) request.getSession().getAttribute("id_user");

        User user = new User();
        user.setIdUser(userId);
        
        Patient patient = new Patient();
        patient.setUser(user);

        theModel.addAttribute("patient", patient);

        return "user/patients/add-patient-dashboard";
    }

 @PostMapping("savePatient")
    public String savePatient(@ModelAttribute("patient") Patient thePatient, Model model) {
        patientService.save(thePatient);
        return "redirect:/user/allPatients";
    }

I try editing the User service from:

@Override
    public void save(User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

to:

@Override
    public void save(User user) {
        List<Patient> patients = user.getPatients();
        patients.forEach(patient -> user.add(patient));
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }

if someone can help me resolve this I would appreciate it since I'm struggling for a very long time with this

enter image description here

CodePudding user response:

Thanks to M Denium I finally solve the issue. I have moved the whole code from addUser to saveUser method:

@RequestMapping("/addPatient")
   public String addPatient(Model theModel) {
            
       Patient patient = new Patient();    
       theModel.addAttribute("patient", patient);
            
       return "user/patients/add-patient-dashboard";
   }
        
       @PostMapping("savePatient")
public String savePatient(@ModelAttribute("patient") Patient thePatient, Model model, HttpServletRequest request) {
    patientService.save(thePatient);

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    UserDetails userD = (UserDetails) auth.getPrincipal();
    User u = userService.findByUsername(userD.getUsername());
    request.getSession().setAttribute("id_user", u.getIdUser());
    
    int userId = (int) request.getSession().getAttribute("id_user");
    User user = userService.findById(userId);
    thePatient.setUser(user);
    patientService.save(thePatient);

    return "redirect:/user/allPatients";
}
  • Related