org.hibernate.NonUniqueObjectException Within GWT application using hibernate through gilead

StackOverflow https://stackoverflow.com/questions/2924259

  •  05-10-2019
  •  | 
  •  

Pergunta

I am working on a project for college that uses GWT, Hibernate and Gilead. Basically for the moment users should be able to add friends and remove them. Also, a user can see if his or her friends are online or not.

My trouble is that when I add a friend that is already related to another friend, I get this error:

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

This is my service class for my gwt application:

public class TestServiceImpl extends PersistentRemoteService implements TestService {

My trouble is here with my implementation class of my service in this method, which is called when a user presses the add friend button on the client-side.

    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();
}

A scenario:

user1 adds user2 as a friend. This works fine, Then user3 adds user2 and the exception is thrown.

Any ideas why and where my logic is going wrong?

Update: Ok, so I have changed my code, and I have removed all the getCurrentASession() calls and replaced with openSession() calls which are closed at the appropriate point, now the error I am getting is:

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
Foi útil?

Solução

It looks to me like you have 3 users with the same user name. As you are using uniqueResult(), you are telling Hibernate that you are expecting only a single value.

Check your database or replace uniqueResult() with List() to see what you get back.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top