问题:
有谁知道如何在不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 尝试重新插入外来对象的情况下合并两个对象?