1

I have the following table, currently I can update the User object to add or remove a role, but I cannot add a role to a new user when it is being created (User's roles are added on the same form on the UI) because the intermediate table User_Role is expecting a User Obj for his ID, so naturally on insert I get a User.User_ID = ?.

Is there any common way to solve this? I was thinking on perhaps trying to get the ID of the inserted user after Save and then calling my update function. I didn't want to to this because I am concerned about performance, specially in the future when bulk uploads may happen.

I am using CrudRepository on my userRepository.

enter image description here

    if(userRequest.getUser().getIdUser() <= -1){
        newUser.setIdUser(0);
        newUser.setIsActiveUs(true);
        newUser.setDateOfJoin(getCurrentDate());
        nuser = usersRepository.save(newUser);
        //Get created user and send it to update() with the roleList?
}
Code Grasshopper
  • 610
  • 1
  • 11
  • 29

1 Answers1

0

is there any data in UserRole that has any value or is it just a xref? I'd probably just get rid of UserRole altogether, create a one to many or one to one mapping from user --> role, and create a shared auto_increment id. That way you can just cascade the data to role on insert to user - all in one transaction.

neal
  • 880
  • 6
  • 11
  • UserRole is there because a user can have more than one role in this application. – Code Grasshopper Mar 09 '16 at 05:46
  • i think you can do this all in one transaction but I'd have to see the mappings. It seems like you could cascade all of these operations using OneToOne from User-->UserRole and viceversa, OneToMany on UserRole --> Role and ManyToOne on Role --> UserRole. – neal Mar 09 '16 at 05:53
  • I'm trying the following http://stackoverflow.com/questions/15943783/how-to-save-a-new-entity-that-refers-existing-entity-in-spring-jpa I'll see how this works. The problem is that the arquitecture of the app should be changed as little as possible at this point in time. – Code Grasshopper Mar 09 '16 at 05:59
  • understood. It gets confusing. The thing I had a hard time wrapping my head around was the fact that I had to, for instance, add the UserRole object to the User class and vice versa - and before committing a transaction, setting User in UserRole and setting UserRole in User. And then add a third table to it.... – neal Mar 09 '16 at 06:06