0

Here is my initial question.

Spring Data JPA Many to Many with extra column User and Roles

Now I have the right tables created, but can't make it work for the update.

Here is the code:

User.java

@Entity
@Table(name = "users")
public class User {

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

  private String username;

  @OneToMany(mappedBy="user", cascade = CascadeType.ALL, orphanRemoval = true,  fetch = FetchType.LAZY)
  private List<UserRole> roles;
  // getters and setters
}

Role.java

@Entity
@Table(name = "roles")
public class Role {

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

  private String name;
  // getters and setters
}

UserRole.java

@Entity
@Table(name = "users_to_role")
public class UserRole  implements Serializable {

  @Id
  @ManyToOne
  @JoinColumn(name = "user_id")
  private User user;

  @Id
  @ManyToOne
  @JoinColumn(name = "role_id")
  private Role role;

  private Date createdAt;

  public UserRole(){}

  public UserRole(User user, Role role, Date date) {
    this.user = user;
    this.role = role;
    this.createdAt = date;
  }

  // getters and setters
}

Controller

@RestController
public class APIController {

  @Autowired
  RoleRepository roleRepository;

  @Autowired
  UserRepository userRepository;


  @ResponseBody
  @RequestMapping(value = "create", method = RequestMethod.GET)
  public String create(){

    //Insert test - WORKING BUT NOT SURE IF ITS RIGHT WAY
    List<UserRole> userRoles = new ArrayList<>();
    Role role = roleRepository.getOne((long) 1);

    //Create user
    User user = new User();
    user.setUsername("test");

    //Create userRole
    userRoles.add(new UserRole(user, role, new Date()));
    user.setRoles(userRoles);

    userRepository.save(user);

    return "created";

  }



  @ResponseBody
  @RequestMapping(value = "edit", method = RequestMethod.GET)
  public String edit(){

    //Edit test - NOT working
    List<UserRole> userRoles = new ArrayList<>();

    Role role = roleRepository.getOne((long) 2);

    //get user from db
    User user = userRepository.getOne((long) 1);

    //Create userRole
    userRoles.add(new UserRole(user, role, new Date()));

    // WAS FIRST ATTEMPT using user.setRoles(userRoles); but got error and use
    //https://stackoverflow.com/questions/9430640/a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-ow
    //user.setRoles(userRoles);

    user.getRoles().clear();
    user.getRoles().addAll(userRoles);


    userRepository.save(user);

    return "done";
  }
}

I am getting this error:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'user_id' cannot be null

VK321
  • 5,768
  • 3
  • 44
  • 47
  • Try to save UserRole instance `userRoleRepository.save(userRole);` before adding it to the `user.getRoles().addAll(savedUserRolesList);` – StanislavL Oct 24 '18 at 11:36
  • @StanislavL I dont have userRoleRepository repository as not sure how i will create it – VK321 Oct 24 '18 at 12:10
  • Then try to save user once, set the list, and save it once more – StanislavL Oct 24 '18 at 12:27
  • @StanislavL - How you will create a repository? what will you put at the place of '?' mark in this line.. public interface UserRoleRepository extends JpaRepository??????, Long> { – VK321 Oct 24 '18 at 12:30
  • @StanislavL - the problem is in the edit. means the user is already saved. why should I save twice more? – VK321 Oct 24 '18 at 12:30
  • You have a newly created user which is not saved. So it cannot pass the user id. – StanislavL Oct 24 '18 at 12:33
  • @StanislavL - An example would be appreciated. All I want is that I am able to save and edit. – VK321 Oct 24 '18 at 12:35
  • About repository. Instead of ??? you should have the UserRole but for key you need a composite key (see https://stackoverflow.com/questions/13032948/how-to-create-and-handle-composite-primary-key-in-jpa) – StanislavL Oct 24 '18 at 12:35
  • @StanislavL - About repository, I do not have Long type in UserRole – VK321 Oct 24 '18 at 12:36
  • Try to set the user in every userRole you have: user.getRoles().clear(); userRoles..forEach(a -> a.setUser(user)); user.getRoles().addAll(userRoles); / And save – L. Figueredo Oct 24 '18 at 17:25
  • @L.Figueredo - can you give a working example in the answer? – VK321 Oct 24 '18 at 18:54
  • Possible duplicate of [Spring-Data-JPA ManyToMany relationship with extra column](https://stackoverflow.com/questions/52648330/spring-data-jpa-manytomany-relationship-with-extra-column) – K.Nicholas Oct 24 '18 at 19:40

0 Answers0