質詢結果:JPA合併在外國實體的重複條目
有誰知道如何無需EntityManager
試圖重新插入外國實體合併嗎?
場景:
剛成立,我的情況下緊密匹配的情形:我有兩個實體
@Entity
@Table(name = "login", catalog = "friends", uniqueConstraints =
@UniqueConstraint(columnNames = "username"))
public class Login implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@Column(name = "username", unique = true, nullable = false, length = 50)
private String username;
@Column(name = "password", nullable = false, length = 250)
private String password;
}
@Entity
@Table(name = "friendshiptype", catalog = "friends")
public class FriendshipType implements java.io.Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "username")
private Login login;
@Column(name = "type", unique = true, length = 32)
private String type;
...//other fields go here
}
無論是Login
實體和FriendshipType
實體單獨保存到數據庫。然後,稍後,我需要合併Login
行和FriendshipType
行。當我打電話entityManager.merge(friendship)
,它試圖插入一個新的Login
這當然會導致以下錯誤
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'myUserName1350319637687' for key 'username'
Error Code: 1062
Call: INSERT INTO friends.login (password, username) VALUES (?, ?)
我的問題,又是我怎麼合併兩個對象,而無需enityManager試圖重新插入異物?
這可能與您的問題無關,但不應該是@JoinColumn(name =「id」)。我見過的所有例子都通過id屬性加入。 –
@Guido Simone我嘗試了你的建議,但沒有改變。 – kasavbere
好的 - 謝謝你讓我知道。希望你得到一些更好的答案。 –