public class User{ @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Group> groups = new HashSet<Group>(); //省略 getter、setter }
User user = new User(); Group g = groupRepo.findById(8);//數據庫查詢 Set gruops = new HashSet<Group>(); gruops.add(g); user.setGroups(gruops); userRepo.save(user);
userRepo.save(user);
保存數據時會出現錯誤detached entity passed to persist
。數據庫
user
時想去級聯保存gruops
。可是gruop已經有id值了。因此報錯。user.setGroups(gruops);
放到保存user
以後。以下:User user = new User(); userRepo.save(user); //先保存user Group g = groupRepo.findById(8);//數據庫查詢 Set gruops = new HashSet<Group>(); gruops.add(g); user.setGroups(gruops); //再設置groups userRepo.save(user); //最後更新user