Hibernate merge

后端 未结 3 1607
孤城傲影
孤城傲影 2021-02-04 12:35

I am testing hibernate and giving this query to

transaction = session.beginTransaction();
city = new City(\"A\");
city  = (City)session.merge(city);
city.setNam         


        
3条回答
  •  忘掉有多难
    2021-02-04 13:09

    I will try to explain using a more concrete example. Suppose you have a scenario like below :

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    User userA = (User)session.get(User.class, 1101);
    transaction.commit();
    session.close();
    // Since session is closed, userA is detached.
    
    session = sessionFactory.openSession();
    transaction = session.beginTransaction();
    User userB = (User)session.get(User.class, 1101);
    //Now here,  userB represents the same persistent row as userA.
    //When an attempt to reattach userA occurs, an exception is thrown
    session.update(userA);
    transaction.commit();
    session.close();
    

    Exception when an attempt to reattach a Detached object, userA is made.

    Exception in thread "main" org.hibernate.NonUniqueObjectException: a   
    different object with the same identifier value was already associated
    with the session:
    
    This is because Hibernate is enforcing that only a single instance of a Persistent    object exists in memory.
    

    To get around the above problem, merge() is used, as shown below :

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    User userA = (User)session.get(User.class, 1101);
    transaction.commit();
    session.close();
    //userA is now detached as session is closed.
    
    session = sessionFactory.openSession();
    transaction = session.beginTransaction();
    User userB = (User)session.get(User.class, 1101);
    User userC = (User)session.merge(userA);
    if (userB == userC) {
      System.out.println("Reattched user is equal");
    }
    transaction.commit();
    session.close();
    

提交回复
热议问题