gpt4 book ai didi

java - JPA 合并导致外国实体重复输入

转载 作者:行者123 更新时间:2023-12-01 07:11:42 25 4
gpt4 key购买 nike

问题:

有人知道如何在不让 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 尝试重新插入外来对象?

最佳答案

这是我解决问题的方法。我终于明白合并 Unresolved 原因是因为 login.id 是由 JPA 自动生成的。因此,由于我确实不需要自动生成的 id 字段,因此我将其从架构中删除并使用 username 作为 @id 字段:

@Entity
@Table(name = "login", catalog = "friends", uniqueConstraints =
@UniqueConstraint(columnNames = "username"))
public class Login implements java.io.Serializable{

private static final long serialVersionUID = 1L;
@Id
@Column(name = "username", unique = true, nullable = false, length = 50)
private String username;
@Column(name = "password", nullable = false, length = 250)
private String password;
}

我想到的另一个解决方案,我没有实现,但如果其他人需要自动生成的 id 字段,可能会对其有所帮助。

不要为合并创建 Login 实例,而是从数据库获取实例。我的意思是,而不是

Login login = new Login(); login.setUsername(username); login.setPassword(password);

不如做

Login login = loginDao.getByUsername(username);

这样,就不会生成新的 id 字段,从而使实体看起来有所不同。

感谢大家的帮助,尤其是@mijer 的耐心帮助,并为其点赞。

关于java - JPA 合并导致外国实体重复输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12902827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com