Spring boot JPA many to many with extra column insert and update issue

时间:2018-10-24 11:25:44

标签: spring hibernate spring-mvc spring-boot jpa

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

0 个答案:

没有答案