2017-03-24 130 views
2

我有以下代碼:春天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; 
    } 
} 
+0

是groupRepository一個JpaRepository?要說清楚的,將創建UserFormGroup實體,而是隻用ID和外鍵GroupModel? –

+0

更多類似的彈簧數據儲存庫,它延伸CrudRepository。它們被創建,但只有id被設置,角色爲空,form_group爲空,並且用戶爲空。 – Servietsky

回答

1

不是100%,但在我看來,問題可能是以下幾點:

的CrudRepository實現save方法,檢查要保存的對象是否是新的或現有的實體。如果它是已經存在的那個,則它執行merge操作。這將是該方案多數民衆贊成在你的情況下發生的groupModel是現有實體。如果添加CascadeType.MERGE操作應該傳播到UserFromGroup實體和堅持他們(合併時的默認行爲

cascade = { CascadeType.PERSIST, CascadeType.REMOVE }

現在的@OneToMany依賴你只有這些級聯選項。實體是新的)。

+0

這似乎工作,但我有以下錯誤'重複條目'1-8關鍵'當我添加到FormGroup中的UserFormGroup。可能是因爲孤兒在創建新孤兒之後被刪除 – Servietsky

+0

通過檢索UserFormGroup(如果它已經存在)並且如果它沒有創建它來修復它。謝謝 – Servietsky

+0

好吧。很高興爲你工作 –