Package javax.persistence

Examples of javax.persistence.Cache


        // Clear the L1
        em.clear();
       
        // Clear the L2 cache
        Cache cache = emf.getCache();
        cache.evictAll();
        assertFalse(cache.contains(CacheableEntity.class, ceid));

        // Find the entity, reloading it into the L2
        em.getTransaction().begin();
        ce = em.find(CacheableEntity.class, ceid);
        assertTrue(em.contains(ce));
        assertTrue(cache.contains(CacheableEntity.class, ceid));
        assertTrue(em.getLockMode(ce) == LockModeType.NONE);
        assertEquals(ce.getName(), "Cached Entity");
        assertEquals(ce.getVersion(), 1);
        em.getTransaction().commit();

        // Create a new EMF -WITHOUT- the L2 enabled.  If the L2 was enabled, the
        // sjvm remote commit provider would evict the entity upon update, throwing
        // off the intent of this variation.
        EntityManagerFactory emf2 = this.createEMF(CacheableEntity.class,
            "openjpa.LockManager", "mixed",
            "openjpa.ConnectionFactoryProperties", "PrintParameters=true");
        EntityManager em2 = emf2.createEntityManager();
       
        // Find + lock, then update the entity and commit
        em2.getTransaction().begin();
        CacheableEntity ce2 = em2.find(CacheableEntity.class, ceid, LockModeType.PESSIMISTIC_FORCE_INCREMENT);
        ce2.setName("Updated Cached Entity");
        em2.getTransaction().commit();
        em2.close();
        emf2.close();

        // Refresh the entity - this will load the entity into the L1 and with storeMode=REFRESH,
        // should also refresh it in the L2
        java.util.Map<String, Object> cacheStoreModeMap = new java.util.HashMap<String, Object>();
        cacheStoreModeMap.put("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH);
        em.refresh(ce, cacheStoreModeMap);

        // Verify the entity was updated
        verifyUpdatedEntity(ce, ceid);

        // Verify loading from the L1
        ce = em.find(CacheableEntity.class, ceid);
       
        // Verify the entity was updated
        verifyUpdatedEntity(ce, ceid);

        // Clear the L1
        em.clear();

        // Assert the L2 contains the entity
        assertTrue(cache.contains(CacheableEntity.class, ceid));

        // Reload the entity from the L2
        ce = em.find(CacheableEntity.class, ceid);
       
        // Verify the entity in the L2 was updated
View Full Code Here


        // Create a new cachable entity
        CacheableEntity ce = createEntity(em);
        int ceid = ce.getId();

        // Clear the L2 cache
        Cache cache = emf.getCache();
        cache.evictAll();
        assertFalse(cache.contains(CacheableEntity.class, ceid));

        // Find the entity, reloading it into the L2
        em.getTransaction().begin();
        ce = em.find(CacheableEntity.class, ceid);
        assertTrue(em.contains(ce));
        assertTrue(cache.contains(CacheableEntity.class, ceid));
        assertTrue(em.getLockMode(ce) == LockModeType.NONE);
        assertEquals(ce.getName(), "Cached Entity");
        assertEquals(ce.getVersion(), 1);
        em.getTransaction().commit();

        // Create a new EMF -WITHOUT- the L2 enabled.  If the L2 was enabled, the
        // sjvm remote commit provider would evict the entity upon delete, throwing
        // off the intent of this variation.
        EntityManagerFactory emf2 = this.createEMF(CacheableEntity.class,
            "openjpa.LockManager", "mixed",
            "openjpa.ConnectionFactoryProperties", "PrintParameters=true");
        EntityManager em2 = emf2.createEntityManager();

        // Find and delete the entity in a separate context with no L2 configured
        em2.getTransaction().begin();
        CacheableEntity ce2 = em2.find(CacheableEntity.class, ceid);
        assertNotNull(ce2);
        em2.remove(ce2);
        em2.getTransaction().commit();
        em2.close();
        emf2.close();

        // Refresh the entity with storeMode=REFRESH.  The entity has been deleted so it will be
        // purged from the L2 cache when the DB load fails.
        java.util.Map<String, Object> cacheStoreModeMap = new java.util.HashMap<String, Object>();
        cacheStoreModeMap.put("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH);
        try {
            em.refresh(ce, cacheStoreModeMap);
            fail("Refresh operation should have thrown an exception");
        } catch (EntityNotFoundException e) {
            // expected exception
        }

        // Try loading from the L1 - OpenJPA will detect the entity was
        // removed in another transaction.
        try {
            ce = em.find(CacheableEntity.class, ceid);
            fail("OpenJPA should have detected the removed entity");
        } catch (EntityNotFoundException e) {
            // expected exception
        }

        // Clear the L1
        em.clear();

        // Assert the L2 no longer contains the entity
        assertFalse(cache.contains(CacheableEntity.class, ceid));

        // Attempt to reload entity from the L2 or database
        ce = em.find(CacheableEntity.class, ceid);

        // Verify the entity was removed from L2 and DB
View Full Code Here

          }
          Class<?> associatedClazz = associated.getClass();
          Method idGetter = associatedClazz
              .getDeclaredMethod("getId");
          EntityManagerFactory emf = em.getEntityManagerFactory();
          Cache emfCache = emf.getCache();
          emfCache.evict(associated.getClass(),
              idGetter.invoke(associated));
        } catch (Exception e) {
          log.warn("Error", e);
        }
      }
View Full Code Here

          Object associated = getter.invoke(entity);
          if (associated == null) {continue;}
          Class<?> associatedClazz = associated.getClass();
          Method idGetter = associatedClazz.getDeclaredMethod("getId");
          EntityManagerFactory emf = em.getEntityManagerFactory();
          Cache emfCache = emf.getCache();
          emfCache.evict(associated.getClass(), idGetter.invoke(associated));
        } catch (Exception e) {
          log.warn("Error", e);
        }
      }
     
View Full Code Here

          }
          Class<?> associatedClazz = associated.getClass();
          Method idGetter = associatedClazz
              .getDeclaredMethod("getId");
          EntityManagerFactory emf = em.getEntityManagerFactory();
          Cache emfCache = emf.getCache();
          emfCache.evict(associated.getClass(),
              idGetter.invoke(associated));
        } catch (Exception e) {
          log.warn("Error", e);
        }
      }
View Full Code Here

          }
          Class<?> associatedClazz = associated.getClass();
          Method idGetter = associatedClazz
              .getDeclaredMethod("getId");
          EntityManagerFactory emf = em.getEntityManagerFactory();
          Cache emfCache = emf.getCache();
          emfCache.evict(associated.getClass(),
              idGetter.invoke(associated));
        } catch (Exception e) {
          log.warn("Error", e);
        }
      }
View Full Code Here

                    employees.put((Integer)args[2], detEmployee);
                    log.trace("Employee (after)  :" + detEmployee);
                    break;

                case ClearCache:
                    Cache cache = em.getEntityManagerFactory().getCache();
                    if (cache != null) {
                        cache.evictAll();
                    }     
                    break;

                case StartTx:
                    em.getTransaction().begin();
                    break;
                case CommitTx:
                    em.getTransaction().commit();
                    break;
                case RollbackTx:
                    em.getTransaction().rollback();
                    break;

                case NewThread:
                    int childToRun = (Integer) args[1];
                    TestThread t1 = new TestThread(childToRun, actions);
                    threads.add(t1);
                    break;
                case StartThread:
                    threads.get((Integer) args[1]).start();
                    break;
                case Notify:
                  // sleep and let other threads has a chance to wait,
                  // otherwise this notify may trigger before the other
                  // thread has a chance to wait.
                  Thread.sleep(500);
                    int notifyThreadid = 0;
                    if (args.length > 1 && args[1] != null) {
                        notifyThreadid = (Integer) args[1];
                    }
                    if (args.length > 2) {
                        Thread.sleep((Integer) args[2]);
                    }
                    if( notifyThreadid == 0) {
                        notifyParent();
                    } else {
                        threads.get(notifyThreadid).notifyThread();
                    }
                    break;
                case Wait:
                    int waitThreadid = threadToRun;
                    if (args.length > 1 && args[1] != null) {
                        waitThreadid = (Integer) args[1];
                    }
                    int waitTime = (int)(waitInMsec / 5);
                    if (args.length > 2 && args[2] != null) {
                        waitTime = (Integer) args[2];
                    }
                    if (waitTime < MinThreadWaitInMs / 2)
                        waitTime = MinThreadWaitInMs / 2;
                    log.trace(">> Started thread " + waitThreadid + " wait for " + waitTime + " ms");
                    if( waitThreadid != 0) {
                        thisThread.wait(waitTime);
                    } else {
                        synchronized (this) {
                            wait(waitTime);
                        }
                    }
                    log.trace("<< Ended wait");
                    break;

                case EmployeeNotNull:
                    id = 1;
                    if (args[1] != null) {
                        id = (Integer)args[1];
                    }
                    employee = employees.get(id);
                    assertNotNull(curAct, employee);
                    break;
                case TestEmployee:
                    id = 1;
                    if (args[1] != null) {
                        id = (Integer)args[1];
                    }
                    employee = employees.get(id);
                    switch (args.length) {
                    case 4:
                        if (args[3] != null) {
                            assertEquals(curAct, saveVersion
                                + (Integer) args[3], employee.getVersion());
                        }
                    case 3:
                        if (args[2] != null) {
                            assertEquals(curAct, (String) args[2], employee
                                .getFirstName());
                        }
                    case 2:
                        if (args[1] != null) {
                            assertEquals(curAct, id.intValue(),
                                employee.getId());
                        }
                        break;
                    case 1:
                        assertNull(curAct, employee);
                    }
                    break;
                case SaveVersion:
                    id = 1;
                    if (args.length > 1) {
                        id = (Integer) args[1];
                    }
                    employee = employees.get(id);
                    saveVersion = employee.getVersion();
                    log.trace("save version= " + saveVersion);
                    break;
                case TestVersion:
                    id = 1;
                    if (args[1] != null) {
                        id = (Integer) args[1];
                    }
                    int increment = (Integer)args[2];
                    employee = employees.get(id);
                    log.trace("test version: expected="
                        + (saveVersion + increment) + ", testing="
                        + employee.getVersion());

                    assertEquals(curAct, saveVersion + increment, employee
                        .getVersion());
                    break;
                case TestLockMode:
                    id = 1;
                    if (args[1] != null) {
                        id = (Integer) args[1];
                    }
                    employee = employees.get(id);
                    LockModeType expectedlockMode = (LockModeType)args[2];
                    LockModeType testinglockMode = em.getLockMode(employee);
                    log.trace("test version: expected=" + expectedlockMode
                        + ", testing=" + testinglockMode);

                    assertEquals(curAct, getCanonical(expectedlockMode),
                        getCanonical(testinglockMode));
                    break;
                case ResetException:
                    thisThread.throwable = null;
                    break;
                case TestException:
                    List<Class<?>> expectedExceptions = null;
                    if (args.length > 2) {
                        expectedExceptions = new ArrayList<Class<?>>();
                        for (int i = 2; i < args.length; ++i) {
                            if (args[i] instanceof Object[]) {
                                for (Object o : (Object[]) args[i]) {
                                    if (o != null && o instanceof Class) {
                                        expectedExceptions
                                            .add((Class<?>) o);
                                    }
                                }
                            } else {
                                if (args[i] != null
                                    && args[i] instanceof Class) {
                                    expectedExceptions
                                        .add((Class<?>) args[i]);
                                }
                            }
                        }
                    }
                    int threadId = threadToRun;
                    if (args.length > 1) {
                        threadId = (Integer) args[1];
                    }
                    if( threadId != -1 ) {
                      // test exception on a specific thread
                        String testExClass = null;
                        Throwable curThrowable = null;
                        boolean exMatched = false;
                        TestThread exThread = threads.get(threadId);
                        curThrowable = exThread.throwable;
                        testExClass = processException(exThread, curAction, curThrowable);

                        if (expectedExceptions != null
                            && expectedExceptions.size() > 0) {
                            for (Class<?> expectedException :
                                expectedExceptions) {
                                if (matchExpectedException(curAct, expectedException,
                                    curThrowable)) {
                                    exMatched = true;
                                    break;
                                }
                            }
                        } else {
                            if (curThrowable == null) {
                                exMatched = true;
                            }
                        }
                        if (!exMatched) {
                            log.trace(testExClass);
                            if (curThrowable != null) {
                                logStack(curThrowable);
                            }
                        }
                        assertTrue(curAct + ":Expecting=" + expectedExceptions
                            + ", Testing=" + testExClass, exMatched);
                        exThread.throwable = null;
                    } else {
                      // test exception in any thread; used for deadlock exception testing since db server
                      // decides on which thread to terminate if deadlock is detected.
                        if (expectedExceptions == null || expectedExceptions.size() == 0) {
                          // Expecting no exception in all threads.
                          boolean noExMatched = true;
              String aTestExClass = "[";
              for (TestThread aThread : threads) {
                Throwable aThrowable = aThread.throwable;
                aTestExClass += processException(aThread, curAction, aThrowable) + ", ";
                  if (aThrowable != null) {
                    noExMatched = false;
                                log.trace(aTestExClass);
                                  logStack(aThrowable);
                                aThread.throwable = null;
                  }
              }
                          assertTrue(curAct + ":Expecting=[no exception]"
                                  + ", Testing=" + aTestExClass + ']', noExMatched);
            } else {
                          // Expecting any exception in any threads.
              boolean aMatched = false;
              String aTestExClass = "[";
              for (TestThread aThread : threads) {
                Throwable aThrowable = aThread.throwable;
                aTestExClass += processException(aThread, curAction, aThrowable) + ", ";

                for (Class<?> anExpectedException : expectedExceptions) {
                  if (matchExpectedException(curAct,
                      anExpectedException, aThrowable)) {
                    aMatched = true;
                    break;
                  }
                }
                if (aMatched) {
                  break;
                } else {
                                if (aThrowable != null) {
                                    logStack(aThrowable);
                                  aThread.throwable = null;
                                }
                }
              }
                          if (!aMatched) {
                              log.trace(aTestExClass);
                          }
                          assertTrue(curAct + ":Expecting=" + expectedExceptions
                              + ", Testing=" + aTestExClass + "]", aMatched);
            }
                    }
                    break;

                case TestInCache:
                    id = 1;
                    boolean expectedInCache = false;
                    if (args.length > 1) {
                        id = (Integer)args[1];
                    }
                    if (args.length > 2) {
                        expectedInCache = (Boolean)args[2];
                    }
                    Cache testCache = em.getEntityManagerFactory().getCache();
                    if (testCache != null) {
                        boolean inCache = testCache.contains(LockEmployee.class, id);                       
                        log.trace("cache.contains(Employee("+id+")) = " + inCache);
                        assertTrue(curAct + ":TestInCache Expecting=" + expectedInCache
                                + ", Testing=" + inCache + "]", inCache == expectedInCache);
                    } else {
                        log.info(curAct+":TestInCache - No Cache found.");
View Full Code Here

       }
  }
 
  @Override
  public AbstractComponent getComponentFromStore(String componentId) {
    Cache c = entityManagerFactory.getCache();
    c.evict(ComponentSpec.class, componentId);
   
    return getComponent(componentId);
  }
View Full Code Here

        }       

  }
 
  private void cleanCacheIfNecessary(String componentId, int latestVersion) {
    Cache c = entityManagerFactory.getCache();
    if (c.contains(ComponentSpec.class, componentId)) {
      EntityManager em = entityManagerFactory.createEntityManager();
      ComponentSpec cs = em.find(ComponentSpec.class, componentId);
      if (cs != null && cs.getObjVersion() < latestVersion) {
        c.evict(ComponentSpec.class, componentId);
      }
      em.close();
    }
  }
View Full Code Here

        };

        OperationStepHandler evictAllHandler = new AbstractMetricsHandler() {
            @Override
            void handle(final ModelNode response, final String name, ManagementLookup stats, OperationContext context) {
                Cache secondLevelCache = stats.getEntityManagerFactory().getCache();
                if (secondLevelCache != null) {
                    secondLevelCache.evictAll();
                }
            }
        };
        jpaHibernateRegistration.registerOperationHandler(OPERATION_EVICTALL, evictAllHandler, evictAll);
View Full Code Here

TOP

Related Classes of javax.persistence.Cache

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.