我有2個實體(我刪除無用的字段):春天JPA保存現有的@OneToMany關係的實體
@Entity
public class ApkPermissions {
@Id
@GeneratedValue
@JsonIgnore
private Long id;
@OneToMany
@Cascade({CascadeType.SAVE_UPDATE})
private Collection<Permission> declaredPermissions;
}
和
@Entity
public class Permission {
@Id
@GeneratedValue
@JsonIgnore
private Long id;
@Column(unique = true)
private String permissionName;
}
當我保存的ApkPermissions實體首次通過一個CrudRepository我沒有問題,但是當我保存另一個ApkPermissions與Permission表中已經存在的一些權限時,會引發一個異常,指出唯一密鑰違反permissionName。
我發現這個解決方案:
http://www.mkyong.com/hibernate/cascade-jpa-hibernate-annotation-common-mistake/
,似乎適合我的情況(是我目前的實現),但它不工作。
我收到以下錯誤信息:
could not execute statement; SQL [n/a]; constraint [UK_l3pmqryh8vgle52647itattb9]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
從MySQL:
UNIQUE KEY `UK_l3pmqryh8vgle52647itattb9` (`permission_name`)
臨時解決方法是retrive所有相應的權限從資源庫通過permissionName搜索。然後保存工作正常。 它在邏輯上是正確的,但我希望存在一個更簡單的過程...
您能否包含異常消息的輸出? – 2016-06-21 20:25:56
我做到了。請注意,現在我改變了關係爲@Pardeep建議 –