我的项目包含一个卡实体和一个用户实体,它们之间存在许多关系。将用户对象插入卡对象时,不会将数据插入数据库的user_card表中。
//控制器
@PostMapping(value = "create")
public Card create( @RequestBody JSONObject data){
Card card = new Card();
String name =(String) data.get("name");
Long columnId = Long.valueOf((Integer)data.get("columnId"));
Long ownerId = Long.valueOf((Integer)data.get("ownerId"));
Integer cardOrder = Integer.valueOf((Integer)data.get("cardOrder"));
String lastDate =(String) data.get("lastDate");
String description =(String) data.get("description");
String assignedUsersId= (String)(data.get("assignedUsers"));
String[] assignedUsersIdArray=assignedUsersId.split(",");
List<User> assignedUsers = new ArrayList<>();
for(int i=0;i<assignedUsersIdArray.length ;i++){
String id = assignedUsersIdArray[i];
if(!id.equals("")) {
assignedUsers.add(userService.getOne(Long.parseLong(id)));
}
}
card.setName(name);
card.setColumnId(columnId);
card.setOwnerId(ownerId);
card.setCardOrder(cardOrder);
card.setLastDate(lastDate);
card.setDescription(description);
card.setUsers(assignedUsers);
return cardService.save(card);
}
//用户实体
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(
name = "user_card",
joinColumns = {@JoinColumn(name = "userid")},
inverseJoinColumns = {@JoinColumn(name="cardid")}
)
@JsonIgnoreProperties("users")
private List<Card> cards = new ArrayList<>();
public List<Card> getCards() {
return cards;
}
//卡实体
@ManyToMany(mappedBy = "cards")
@JsonIgnoreProperties("cards")
private List<User> users = new ArrayList<>();
// @JsonManagedReference
public void setUsers(List<User> users) {
for(User user : users){
this.users.add(user);
}
}
public List<User> getUsers() {
return users;
}
答案 0 :(得分:0)
您应将cascade
移至卡实体。由于您希望插入卡中,因此会触发插入用户,而不是其他方式。