{code:java} @Entity @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "item") public class CacheableItem { private Long id; private String name;
public CacheableItem() { }
public CacheableItem(String name) { this.name = name; }
@Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } } {code}
Test case: {code:java} @Test public void testUpdateAndRefresh() { // prepare data Session s = openSession(); s.beginTransaction(); CacheableItem item = new CacheableItem( "item" ); s.save( item ); s.getTransaction().commit(); s.close();
Session s1 = openSession(); s1.beginTransaction();
CacheableItem item1 = s1.get( CacheableItem.class, item.getId() ); // into persistent context item1.setName( "some name" );
s1.flush(); s1.clear(); // clear persistent context s1.refresh( item1 );
item1 = s1.get( CacheableItem.class, item.getId() ); assertEquals( "some name", item1.getName() );
// open another session Session s2 = sessionFactory().openSession(); try { s2.beginTransaction(); CacheableItem item2 = s2.get( CacheableItem.class, item.getId() );
assertEquals( "item", item2.getName() );
} catch (PessimisticLockException expected) { // expected if MVCC is not enabled } catch (Exception e) { throw e; } finally { s2.getTransaction().rollback(); s2.close(); }
s1.getTransaction().rollback(); s1.close();
} {code}
hibernate.properties {code:java} hibernate.dialect org.hibernate.dialect.H2Dialect hibernate.connection.driver_class org.h2.Driver hibernate.connection.url jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=true hibernate.connection.username sa ... {code} note: MVCC should be *enabled* in connection url |
|