【问题标题】:org.hibernate.NonUniqueObjectException Within GWT application using hibernate through gileadorg.hibernate.NonUniqueObjectException 在 GWT 应用程序中通过 gilead 使用休眠
【发布时间】:2010-05-27 19:32:36
【问题描述】:

我正在开发一个使用 GWT、Hibernate 和 Gilead 的大学项目。基本上目前用户应该能够添加和删除朋友。此外,用户可以查看他或她的朋友是否在线。

我的麻烦是当我添加一个已经与另一个朋友相关的朋友时,我收到了这个错误:

org.hibernate.NonUniqueObjectException: a different object with the same identifier value     was already associated with the session: [com.example.client.YFUser#4]

这是我的 gwt 应用程序的服务类:

public class TestServiceImpl extends PersistentRemoteService implements TestService {

我的麻烦在于我在此方法中的服务实现类,当用户在客户端按下 addfriend 按钮时调用该方法。

    public void addYFUserFriend(String userName){
            //this retrieves the current user
    YFUser user = (YFUser)getSession().getAttribute(SESSION_USER);

    Session session = com.example.server.HibernateUtil.getSessionFactory().getCurrentSession();

    session.beginTransaction();

    YFUser friend = (YFUser) session.createQuery("select u FROM YFUser u where u.username = :username").setParameter("username", userName).uniqueResult();
    System.out.println("user " + friend.getUsername() + " Found");

    user.getFriends().add(friend);

    friend.getBefriended().add(user);
            session.update(user);
            session.update(friend);

    session.getTransaction().commit();
}

一个场景:

user1user2 添加为好友。这工作正常,然后 user3 添加 user2 并抛出异常。

任何想法为什么我的逻辑出错以及在哪里出错?

更新:好的,所以我已经更改了我的代码,我已经删除了所有 getCurrentASession() 调用并替换为在适当的时候关闭的 openSession() 调用,现在我得到的错误是:

com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract void com.example.client.TestService.addYFUserFriend(java.lang.String)' threw an unexpected exception: org.hibernate.NonUniqueResultException: query did not return a unique result: 3

【问题讨论】:

  • Hibernate Session 的范围是什么/它在哪里管理?在给出的示例中,您使用的是 getCurrentSession()。前端是否有打开新会话的过滤器?在许多用户之间共享一个永无止境的休眠会话是灾难的一个公式:)
  • 我在前端没有过滤器,我真的不知道它是什么,可以让我了解如何不共享会话。(我真的不知道我是否)。我只打开一个会话将用户发送到客户端,这允许他们登录,然后打开一个会话以在他们注销或更新某些内容时保存用户。关于如何不共享会话的提示会很棒?
  • 我也在使用一个 hibernateUtil 类来管理会话,它类似于这个例子中的类,一些修改用于 gilead,code.google.com/webtoolkit/articles/…
  • 从休眠的角度来看,当您应该说 openSession() 时,您似乎在说 getCurrentSession(),您的两个 Web 用户似乎都在尝试使用相同的休眠会话。但是,我对 Gilead 的了解只是暂时的,所以我无法明智地评论 Session 管理在 Gilead 启用的情况下应该如何工作,抱歉我不能提供更多帮助:(

标签: java hibernate gwt gilead


【解决方案1】:

在我看来,您有 3 个用户名相同的用户。当您使用uniqueResult() 时,您是在告诉 Hibernate 您只需要一个值。

检查您的数据库或将 uniqueResult() 替换为 List() 以查看返回的内容。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2018-12-07
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 2023-04-04
    • 2022-11-03
    相关资源
    最近更新 更多