-1
我在很多帖子中發現了這個問題,但是我找不到解決方案。 我有一個實體:JPA Eclipse未能在合併()調用上更新外鍵
@Entity
@Table(name="UTENTI")
@NamedQueries({
@NamedQuery(name="Utenti.findAll", query="SELECT u FROM Utenti u"),
@NamedQuery(name="Utenti.findByEmail", query="SELECT u FROM Utenti u WHERE u.userId = :mail")
})
public class Utenti implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="ID_UTENTE", nullable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private BigDecimal id;
@Column(name="USER_ID",unique=true)
private String userId;
private String cognome;
@Temporal(TemporalType.DATE)
private Date dataDiNascita;
private String nome;
private String password;
private String ruolo;
@OneToMany(mappedBy="user",cascade=CascadeType.ALL)
private List<Form> forms;
@ManyToMany(mappedBy="users",cascade=CascadeType.ALL)
private List<Groups> groups;
@OneToMany(mappedBy="utente",cascade=CascadeType.ALL)
private List<CodicePromozionale> codes;
@OneToMany(mappedBy="owner",cascade=CascadeType.ALL)
private List<PacchettoAcquistato> acquisti;
/*getters and setters*/
並形成其他單位:
@Entity
@Table(name="GROUPS")
public class Groups implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="GROUPID", nullable=false)
private String groupId;
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name="USER_GROUP",joinColumns={@JoinColumn(name="GROUPID",referencedColumnName="GROUPID")},inverseJoinColumns={@JoinColumn(name="USERID",referencedColumnName="USER_ID")})
private List<Utenti> users;
如果我改變我的userId的無狀態bean中,然後調用合併,像這樣:
this.user.setUserId(newUserId);
this.em.merge(user);
其中this.em是EntityManager
我收到此錯誤:
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507- 3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`traveldreamdb`.`user_group`, CONSTRAINT `FK_USER_GROUP_USERID` FOREIGN KEY (`USERID`) REFERENCES `UTENTI` (`USER_ID`))
Error Code: 1451
Call: UPDATE UTENTI SET USER_ID = ? WHERE (ID_UTENTE = ?)
bind => [2 parameters bound]
爲什麼會發生這種情況,如果我指定cascadeType.ALL?我該如何解決它?
user_group是通過在userId和groupId上進行聯接而創建的表,如您在註釋它的實體組中所看到的。我該怎麼做?爲什麼不自動更新? – gcc
我不認爲JPA在更新時處理引用。因此,首先必須刪除(或將user_id更改爲任何其他值)user_group中與user_id引用的行。只有這樣你才能執行UPDATE操作。 –
我如何更改user_id我user_group?我沒有用於user_group的實體,因爲它是作爲連接表生成的。 CascadeType的含義是什麼? @Sabuj Hassan – gcc