I am new user and having an issue with rolling back transactions in Hibernate. I started with the simple example for storing cat objects (with fields name, sex, weight). I am using the source code below for testing transactions. I start a transaction, create a cat named fred, do a query for cats, and print the results and it shows Fred. Then, I create a second cat named Wally, rollback the transaction, do a query for cats, and it lists 1 cat, Wally, even though I have rolled back the transaction. After the program completes, the transaction does appear to be rolled back as the database table has no entries in it.
Can someone explain why my second query gets the one cat back even though I rolled back the transaction? Is the transaction not rolled back until I close the session or is there something about the objects being cached in the session?
Thanks in advance!
Robert
==============SOURCE=====================
SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("Beginning transaction");
Transaction tx = session.beginTransaction();
System.out.println("Inserting Fred");
Cat fred = new Cat();
fred.setName("Fred");
fred.setSex('M');
fred.setWeight(14.4f);
session.save(fred);
System.out.println();
System.out.println("Listing Cats");
Query query = session.createQuery("from Cat");
List cats = query.list();
for (int i = 0; i < cats.size(); i++) {
System.out.println(cats.get(i));
}
System.out.println();
System.out.println("Inserting Wally");
Cat wally = new Cat();
wally.setName("Wally");
wally.setSex('F');
wally.setWeight(7.4f);
session.save(wally);
System.out.println("Rolling back transaction");
tx.rollback();
System.out.println();
System.out.println("Listing Cats");
query = session.createQuery("from Cat");
cats = query.list();
for (int i = 0; i < cats.size(); i++) {
System.out.println(cats.get(i));
}
session.close();
==============OUTPUT=====================
Beginning transaction
Inserting Fred
Listing Cats
(Fred, M, 14.4)
Inserting Wally
Rolling back transaction
Listing Cats
(Wally, F, 7.4)
=========================================
|