loungerdork
loungerdork

Reputation: 991

Hibernate collection not updated when records inserted externally

I've a mapped collection that is not updated when I add items to that collection externally, in another application.

Second-level caching is disabled.

Example...

session = HibernateDataSource.openSession();
User dao = (User) session.load(User.class, 2434152);
// No items now, this gives 0
System.err.println(dao.getItems().size());
session.close();
Thread.sleep(10000);
// Add an item outside, e.g. in PMA
session = HibernateDataSource.openSession();
HibernateDataSource.getSessionFactory().evict(User.class);
HibernateDataSource.getSessionFactory().evict(UserItem.class);
HibernateDataSource.getSessionFactory().evictCollection(User.class.getName() + ".items");
dao = (User) session.load(User.class, 2434152);
// Still zero
System.err.println(dao.getItems().size());
session.close();

I've tried several solutions when googling, e.g. setting the collection as dirty. None worked.

Is there something else that I haven't looked at?

P.S. First tried on Hibernate 3.2.7. Upgraded to 3.3.2, no difference.

Upvotes: 2

Views: 1418

Answers (1)

loungerdork
loungerdork

Reputation: 991

After spending 95% of the time hacking into Hibernate, it has been exonerated.

The issue arose due to MySQL's query caching, which, despite the name, also caches resultsets for repeatable reads. This is due to the nature of multi-versioning on MySQL's InnoDB.

In order to "set a new time point for a snapshot", wrap your unit of work in a transaction, even if there are only select queries.

Further reading...

http://forums.mysql.com/read.php?39,416790,416790

http://dev.mysql.com/doc/refman/5.0/en/query-cache.html

Upvotes: 1

Related Questions