@Test(expectedExceptions = OptimisticLockException.class) public void testOptimisticLockException() { ComponentSpec cs = createComponentSpec( Long.toString(1), "chris", "cs", "type1", "chris", Collections.<Tag>emptyList(), Collections.<String, String>emptyMap()); em.getTransaction().begin(); em.persist(cs); em.getTransaction().commit(); em.clear(); Assert.assertFalse(em.contains(cs)); em.getTransaction().begin(); ComponentSpec orig = em.find(ComponentSpec.class, Long.toString(1)); orig.setComponentName("revisedName"); em.getTransaction().commit(); em.clear(); ComponentSpec current = em.find(ComponentSpec.class, Long.toString(1)); Assert.assertEquals(current.getObjVersion(), 1); Assert.assertEquals(cs.getObjVersion(), 0); em.getTransaction().begin(); em.merge(cs); em.getTransaction() .commit(); // optimistic lock exception should be thrown as there has been an intervening // commit }
private ComponentSpec createComponentSpec( String id, String userId, String name, String type, String owner, List<Tag> tags, Map<String, String> views) { ComponentSpec cs = new ComponentSpec(); cs.setComponentId(id); cs.setCreatorUserId(userId); cs.setComponentName(name); cs.setComponentType(type); cs.setOwner(owner); cs.setReferencedComponents(new ArrayList<ComponentSpec>()); List<ViewState> viewStates = new ArrayList<ViewState>(); for (Entry<String, String> e : views.entrySet()) { ViewState vs = new ViewState(); ViewStatePK viewStatePK = new ViewStatePK(); viewStatePK.setComponentId(cs.getComponentId()); viewStatePK.setViewType(e.getKey()); vs.setViewStatePK(viewStatePK); vs.setViewInfo(e.getValue()); viewStates.add(vs); } cs.setViewStateCollection(viewStates); cs.setTagAssociationCollection(new ArrayList<TagAssociation>()); for (Tag aTag : tags) { TagAssociation association = new TagAssociation(); TagAssociationPK tagPK = new TagAssociationPK(); tagPK.setComponentId(cs.getComponentId()); tagPK.setTagId(aTag.getTagId()); association.setTagAssociationPK(tagPK); association.setTagProperty(aTag.getTagProperty()); cs.getTagAssociationCollection().add(association); } return cs; }