【发布时间】:2012-10-05 20:27:06
【问题描述】:
问题:
有没有人知道如何在没有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 我尝试了你的建议,但没有改变。
-
好的 - 感谢您告诉我。希望你能得到更好的答案。