我有以下代碼:春天JPA創建了空實體值
groupModel.getUserFormGroups().clear();
for(MemberDTO member : group.getMembers()){
User u = userRepository.findByEmail(member.getEmail());
System.out.println(member.getEmail() + " " + groupModel.getName() + " " + member.getRole());
if(u == null){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
groupModel.getUserFormGroups().add(new UserFormGroup(u, groupModel, UserFormGroupRole.ADMIN));
}
try{
groupRepository.save(groupModel);
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (DataIntegrityViolationException e){
System.out.println(e.getMessage());
System.out.println(e.getClass());
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build();
}
當我運行此,新UserFormGroups
有一個ID和所有其他字段爲空。完全更新ManyToOne關係有什麼問題嗎?
在組實體我有以下一對多關係:
@OneToMany(targetEntity=UserFormGroup.class, cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, fetch = FetchType.EAGER, mappedBy = "formGroup", orphanRemoval=true)
private Set<UserFormGroup> userFormGroups = new HashSet<>();
而且UserFormGroup關係是這樣的:
@Entity
@Table(uniqueConstraints={
@UniqueConstraint(columnNames = {"user", "form_group"})
})
public class UserFormGroup implements Serializable{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private long id;
@ManyToOne
@JoinColumn(name = "user",referencedColumnName = "id")
private User user;
@ManyToOne
@JoinColumn(name = "form_group", referencedColumnName = "id")
private FormGroup formGroup;
@Column(name = "role")
private UserFormGroupRole role;
public UserFormGroup() {
}
public UserFormGroup(User user, FormGroup group, UserFormGroupRole role) {
this.user = user;
this.formGroup = group;
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public FormGroup getFormGroup() {
return formGroup;
}
public void setFormGroup(FormGroup formGroup) {
this.formGroup = formGroup;
}
public UserFormGroupRole getRole() {
return role;
}
public void setRole(UserFormGroupRole role) {
this.role = role;
}
}
是groupRepository一個JpaRepository?要說清楚的,將創建UserFormGroup實體,而是隻用ID和外鍵GroupModel? –
更多類似的彈簧數據儲存庫,它延伸CrudRepository。它們被創建,但只有id被設置,角色爲空,form_group爲空,並且用戶爲空。 – Servietsky