org.hibernate.nonuniqueObjectException在GWT应用程序中使用Hibernate通过Gilead
题
我正在研究一个使用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 {
我的麻烦是在此方法中使用我的服务的实现类别,当用户按下用户时称为 添加好友 客户端上的按钮。
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();
}
场景:
用户1 添加 用户2 作为一个朋友。这样可以正常工作 用户3 添加 用户2 并抛出了例外。
有什么想法,为什么我的逻辑出错了?
更新:好的,所以我已经更改了代码,并且已经删除了所有的代码 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
解决方案
在我看来,您有3个具有相同用户名的用户。当您使用 uniqueResult()
, ,您告诉Hibernate,您只期望一个值。
检查您的数据库或更换 uniqueResult()
和 List()
看看你回来了。
不隶属于 StackOverflow