hi,
I am using an online tutorial to learn hibernate I am facing problem to understand the following piece of information and code...
In session, Hibernate guarantees no two Persistent objects represent the same row. Again, this guarantee no
longer holds with Detatched objects. In fact, this problem can create very unwanted consequences. Explore
the code below.
Code:
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
BallPlayer p1 = (BallPlayer)session.get(BallPlayer.class, 1L);
transaction.commit();
session.close();
//p1 is now detached.
session = sessionFactory.openSession();
transaction = session.beginTransaction();
BallPlayer p2 = (BallPlayer)session.get(BallPlayer.class, 1L);
//Oops! p2 represents the same persistent row as p1.
//When an attempt to reattach p1 occurs, an exception is thrown
session.update(p1);
transaction.commit();
session.close();
This code throws an exception when an attempt to reattach the Detached object at p1 is made.
Exception in thread "main" org.hibernate.NonUniqueObjectException: a
different object with the same identifier value was already associated
with the session: [com.intertech.domain.BallPlayer#1]
at
org.hibernate.engine.StatefulPersistenceContext.checkUniqueness
(StatefulPersistenceContext.java:613)
...
This is because Hibernate is trying to reinforce the guarantee that only a single instance of a Persistent object
exist in memory.
BUT when I am trying to run a similar code it dosent throw any exception as expected...
My code is following...
Code:
public static void main(String[] args) {
SessionFactory sessions =
new AnnotationConfiguration().configure().buildSessionFactory();
Session session1 = sessions.openSession();
session1.beginTransaction();
Person p2 = (Person) session1.load(Person.class, 1);
session1.getTransaction().commit();
session1.close();
session1 = sessions.openSession();
session1.beginTransaction();
Person p3 = (Person) session1.load(Person.class, 1);
System.out.println(p3.getName());
session1.update(p2);
session1.getTransaction().commit();
session1.close();
please provide some insight....Thanks in advance...
veeru