I have a problem trying to delete, then save a user in an application using the PostgreSQL database. Here is my controller:
@PostMapping
public String addCalories(@RequestParam Integer consumedKcal, HttpServletRequest request){
User u = (User) request.getSession().getAttribute("u");
User newUser = this.userService.save(u.getUsername(), u.getPassword(), u.getAge(), u.getGender(), u.getHeight(), u.getWeight(), u.getGoal(), u.getActivity_rate(), u.getKcal_needed(), u.getBmi(), consumedKcal);
return "redirect:/home";
}
Here is my service method:
@Override
@Transactional
public User save(String username, String password, Integer age, String gender, Float height, Float weight, String goal, String activity_rate, Integer kcal_needed, Float bmi, Integer kcal_consumed) {
this.userRepository.deleteUserByUsername(username);
User u = new User(username, password, age, gender, height, weight, goal, activity_rate, kcal_needed, bmi, kcal_consumed);
return this.userRepository.save(u);
}
The repository:
public interface UserRepository extends JpaRepository<User, Integer> {
User findUserByUsername(String username);
void deleteUserByUsername(String username);
}
The entity:
@Data
@Entity
@Table(name = "user_app")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer username_id;
private String username;
private String password;
private Integer age;
private String gender;
private Float height;
private Float weight;
private String goal;
private String activity_rate;
private Integer kcal_needed;
private Float bmi;
private Integer kcal_consumed;
private Integer water_consumed;
}
The JPA method delete works fine, it deletes the user. But I get this error duplicate key value violates unique constraint "user_username_key" Detail: Key (username)=(test) already exists. I don't know how to solve it. Any help is welcome.