How to insert data in multiple tables in a single url through POST API springboot

123 Views Asked by At

I have a 2 entities UserDetails and Skills . Many users can have many skills and the user needs to enter the skill rating also. I have 3 tables skill,userdetails and skillratings. In skillratings userid and skillid are the foreign key. I want to enter the details of users and skill before the skillrating in a single post method. If I use Casacade.ALL the skill which is already present get also entered into the database. Here is the code for all 3 entities (https://i.stack.imgur.com/92pqk.jpg)(https://i.stack.imgur.com/qCoPp.jpg)(https://i.stack.imgur.com/0FRhX.jpg)

I just want to add the userdetails,skills and skillrating data and no repeated data into the skill table while adding data into skillrating data.

1

There are 1 best solutions below

0
Sammie On

Ok this what you do. Firstly you create a class maybe you call it UserRegRequest. This will not be an entity just an object, do ensure to add the getters, setters, all and no arg constructor.This class will have all the fields in the users entity , skill entity and then in the skill rating entity . then you set the values of the skills,userDetails and skillRating from the userRegRequest for and then setUserSkill an so on here is an example of a similar logic in my project so you understand

public class Location {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "location_sequence")
private long id;
private String city;
private String street;
private String district;

}

public class RegCompletion {
private String fullName;
private String Street;
private String phoneNumber;
private String district;
private String city;

}

 public ResponseEntity<Object> complete_registration(RegCompletion regCompletion) {
    UserEntity user = userRepository.findByPhoneNumber(regCompletion.getPhoneNumber());

    Boolean enabled = user.isAccountEnabled();
    if(enabled == true){
        user.setFullName(regCompletion.getFullName());
        //another entity
        Location location = new Location();
        location.setStreet(regCompletion.getStreet());
        location.setCity(regCompletion.getCity());
        location.setDistrict(regCompletion.getDistrict());

        //saving location
        locationRepository.save(location);

        //setting the users location
        user.setLocation(location);
        userRepository.save(user);

        return Builder.responseHandler(201, "Account created successfully",findByPhoneNumber(user.getPhoneNumber()));
    }else
    return Builder.responseHandler(451, "You account has not yet been enabled. Verify you phoneNumber first",null);
}