gpt4 book ai didi

java - 在一对多关系中获取表中的重复条目

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:05 25 4
gpt4 key购买 nike

我正在学习 jpa 并决定做一个基本的 web 应用程序,用户可以在其中发布消息,因此用户有很多消息。问题是,当我向用户的消息集合添加一条消息时,我在消息表中得到了重复的条目。 (请注意,我有两个表的所有者 ID 在 Message 上,没有连接表)。

这是对话:

第一条消息 -> 拉里说:你好约翰

第二条消息 -> 拉里说:你在吗?

第三条消息 -> 约翰说:是的

第四条消息 -> 拉里说:好的

第五条信息 -> 约翰说:很好

这是我在屏幕上得到的:

拉里:你好约翰

拉里你好约翰

拉里:你在吗?

约翰:是的

拉里:你好约翰

拉里:你在吗?

拉里:好的

约翰:是的

约翰:很好

表格内容为:

+----+----------------+----------+
| id | message | owner_id |
+----+----------------+----------+
| 1 | Hello John | NULL | <- Why the NULL fields?
| 2 | Hello John | NULL |
| 3 | Are you there? | NULL |
| 4 | Yep | NULL |
| 5 | Hello John | 1 |
| 6 | Are you there? | 1 |
| 7 | ok | 1 |
| 8 | Yep | 2 |
| 9 | fine | 2 |
+----+----------------+----------+

这些是我拥有的类及其映射。

@Entity

public class User implements Serializable {

@Id
@GeneratedValue
private Long id;
private String username;
private String password;

@OneToMany (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name="owner_id")
private List<Message> messages; ...and all of its corresponding getters and setters

@Entity
public class Message implements Serializable {

@Id
@GeneratedValue
private Long id;
private String message;

@ManyToOne
private User owner; //...and all of its corresponding getters and setters

这是保存用户的相关 jsp scriptlet 部分:

User user = (User)session.getAttribute("user");
user.getMessages().add(new Message(request.getParameter("message")));

FactoryDAO.getInstance().getUserDAO().update(user);

更新(用户)方法:

public void update(User user) {
initEntityManager(); <- method in the superclass which initializes the entityManager
tx.begin();
entityManager.merge(user);
entityManager.flush();
tx.commit();
closeEntityManager();
}

你能帮我找出这里出了什么问题吗?谢谢!

最佳答案

这可能与您创建新 User 对象(未在您的代码中显示)的方式有关。

除此之外,您还可以尝试以下几件事:

  1. update 方法中使用 persist 而不是 merge
  2. 使用 Set 而不是 List 来存储 messages
  3. 确保在您的两个实体中覆盖equalshashCode

关于java - 在一对多关系中获取表中的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8197462/

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