use of org.jpwh.shared.util.TestData in project microservices by pwillhan.
the class SecondLevel method storeTestData.
public CacheTestData storeTestData() throws Exception {
UserTransaction tx = TM.getUserTransaction();
tx.begin();
EntityManager em = JPA.createEntityManager();
Long[] itemIds = new Long[3];
Long[] userIds = new Long[3];
User johndoe = new User("johndoe");
em.persist(johndoe);
userIds[0] = johndoe.getId();
User janeroe = new User("janeroe");
em.persist(janeroe);
userIds[1] = janeroe.getId();
User robertdoe = new User("robertdoe");
em.persist(robertdoe);
userIds[2] = robertdoe.getId();
Item item = new Item("Item One", CalendarUtil.TOMORROW.getTime(), johndoe);
em.persist(item);
itemIds[0] = item.getId();
for (int i = 1; i <= 3; i++) {
Bid bid = new Bid(item, robertdoe, new BigDecimal(9 + i));
item.getBids().add(bid);
em.persist(bid);
}
item = new Item("Item Two", CalendarUtil.TOMORROW.getTime(), johndoe);
em.persist(item);
itemIds[1] = item.getId();
for (int i = 1; i <= 1; i++) {
Bid bid = new Bid(item, janeroe, new BigDecimal(2 + i));
item.getBids().add(bid);
em.persist(bid);
}
item = new Item("Item_Three", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
em.persist(item);
itemIds[2] = item.getId();
for (int i = 1; i <= 1; i++) {
Bid bid = new Bid(item, johndoe, new BigDecimal(3 + i));
item.getBids().add(bid);
em.persist(bid);
}
tx.commit();
em.close();
// Warm up the cache properly
tx.begin();
em = JPA.createEntityManager();
// We load all the User instances into the second-level cache
// here because NONSTRICT_READ_WRITE strategy doesn't insert
// them into the second-level cache when persist() is called,
// only when they are loaded from the database. And we need
// to do this in a new transaction, or TwoPhaseLoad doesn't
// put it in the cache.
em.createQuery("select u from User u").getResultList();
// collection is loaded.
for (Long itemId : itemIds) {
em.find(Item.class, itemId).getBids().size();
}
tx.commit();
em.close();
JPA.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics().clear();
CacheTestData testData = new CacheTestData();
testData.items = new TestData(itemIds);
testData.users = new TestData(userIds);
return testData;
}
Aggregations