/** * Get the {@code Statistics} object from the underlying {@code SessionFactory}. If it isn't hibernate that is * used return {@code null}. * * @param emf an {@code EntityManagerFactory} * @return the {@code Statistics} from the underlying {@code SessionFactory} or {@code null}. */ private Statistics getStatistics(EntityManagerFactory emf) { try { SessionFactory sf = emf.unwrap(SessionFactory.class); return sf.getStatistics(); } catch (PersistenceException pe) { return null; } }
@Test(enabled = false) public <T extends ObjectType> void perfTest() throws Exception { Statistics stats = getFactory().getStatistics(); stats.setStatisticsEnabled(true); final File OBJECTS_FILE = new File("./src/test/resources/10k-users.xml"); List<PrismObject<? extends Objectable>> elements = prismContext.parserFor(OBJECTS_FILE).parseObjects(); long previousCycle = 0; long time = System.currentTimeMillis(); for (int i = 0; i < elements.size(); i++) { if (i % 500 == 0) { LOGGER.info("Previous cycle time {}. Next cycle: {}", new Object[]{ (System.currentTimeMillis() - time - previousCycle), i}); previousCycle = System.currentTimeMillis() - time; } PrismObject<T> object = (PrismObject<T>) elements.get(i); repositoryService.addObject(object, null, new OperationResult("add performance test")); } LOGGER.info("Time to add objects ({}): {}", new Object[]{elements.size(), (System.currentTimeMillis() - time)}); stats.logSummary(); }
@Test public void statisticsAPI() { log.info("... statisticsAPI ..."); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); List<Author> authors = em.createQuery("SELECT a FROM Author a", Author.class).getResultList(); for (Author a : authors) { log.info(a.getFirstName() + " " + a.getLastName() + " wrote " + a.getBooks().size()); } SessionFactory sessionFactory = emf.unwrap(SessionFactory.class); Statistics stats = sessionFactory.getStatistics(); long queryCount = stats.getQueryExecutionCount(); long collectionFetchCount = stats.getCollectionFetchCount(); log.info("QueryCount: "+queryCount); log.info("CollectionFetchCount: "+collectionFetchCount); em.getTransaction().commit(); em.close(); }
@Test public void test() { SessionFactory factory = SessionFactoryProvider .getInstance().provide(Context.class); Statistics statistics = factory.getStatistics(); SecondLevelCacheStatistics secondStat = factory.getStatistics().getSecondLevelCacheStatistics(GameUser.class.getName()); deleteAll(); logger.info("==========>>>deleteAll: second level cache hits: " + statistics.getSecondLevelCacheHitCount()); logger.info("==========>>>deleteAll: query execution hits: " + statistics.getQueryExecutionCount()); logger.info("==========>>>deleteAll: element count in mem: " + secondStat.getElementCountInMemory()); intsert5(); logger.info("==========>>>intsert5: second level cache hits: " + statistics.getSecondLevelCacheHitCount()); logger.info("==========>>>intsert5: query execution hits: " + statistics.getQueryExecutionCount()); logger.info("==========>>>intsert5: element count in mem: " + secondStat.getElementCountInMemory()); doSomeThing(); logger.info("==========>>>doSomeThing: second level cache hits: " + statistics.getSecondLevelCacheHitCount()); logger.info("==========>>>doSomeThing: query execution hits: " + statistics.getQueryExecutionCount()); logger.info("==========>>>doSomeThing: element count in mem: " + secondStat.getElementCountInMemory()); deleteAll(); logger.info("==========>>>deleteAll: second level cache hits: " + statistics.getSecondLevelCacheHitCount()); logger.info("==========>>>deleteAll: query execution hits: " + statistics.getQueryExecutionCount()); logger.info("==========>>>deleteAll: element count in mem: " + secondStat.getElementCountInMemory()); }
private Map<String, Long> getStatsValues(Collection<Class> entities) { Statistics stats = getStats(); Map<String, Long> statistics = new HashMap<String, Long>(); statistics.put("Number of connection requests", stats.getConnectCount()); statistics.put("Sessions opened", stats.getSessionOpenCount()); // statistics.put("Sessions closed", stats.getSessionCloseCount()); statistics.put("Transactions", stats.getTransactionCount()); // statistics.put("Successful transactions", stats.getSuccessfulTransactionCount()); // statistics.put("Successful transactions", stats.getSuccessfulTransactionCount()); statistics.put("Queries executed", stats.getQueryExecutionCount()); for(Class entity : entities) { EntityStatistics eStats = stats.getEntityStatistics(entity.getName()); statistics.put(entity.getSimpleName() + " Fetched", eStats.getFetchCount()); statistics.put(entity.getSimpleName() + " Loaded", eStats.getLoadCount()); statistics.put(entity.getSimpleName() + " Inserted", eStats.getInsertCount()); statistics.put(entity.getSimpleName() + " Deleted", eStats.getDeleteCount()); statistics.put(entity.getSimpleName() + " Updated", eStats.getUpdateCount()); } return statistics; }
@Test public void test() { Cache cache = entityManager.getEntityManagerFactory().getCache(); cache.evictAll(); Statistics statistics = ((Session)(entityManager.getDelegate())).getSessionFactory().getStatistics(); statistics.clear(); CommonCourt commonCourt = testPersistenceObjectFactory.createCcCourt(CommonCourtType.APPEAL); commonCourtRepository.findOne(commonCourt.getId()); commonCourtRepository.findOne(commonCourt.getId()); Assert.assertTrue(cache.contains(CommonCourt.class, commonCourt.getId())); Assert.assertTrue(cache.contains(CommonCourtDivision.class, commonCourt.getDivisions().get(0).getId())); Assert.assertTrue(cache.contains(CommonCourtDivision.class, commonCourt.getDivisions().get(1).getId())); cache.evict(CommonCourt.class); cache.evict(CommonCourtDivision.class); Assert.assertFalse(cache.contains(CommonCourt.class, commonCourt.getId())); Assert.assertFalse(cache.contains(CommonCourtDivision.class, commonCourt.getDivisions().get(0).getId())); Assert.assertFalse(cache.contains(CommonCourtDivision.class, commonCourt.getDivisions().get(1).getId())); Assert.assertEquals(5, statistics.getSecondLevelCachePutCount()); // 1 commonCourt + 2 ccDivision + 2 ccDivisionType Assert.assertEquals(2, statistics.getSecondLevelCacheHitCount()); Assert.assertEquals(0, statistics.getSecondLevelCacheMissCount()); }
private void counter(MeterRegistry registry, String name, String description, ToDoubleFunction<Statistics> f, String... extraTags) { FunctionCounter.builder(name, stats, f) .tags(tags) .tags(extraTags) .description(description) .register(registry); }
private static EntityManagerFactory createEntityManagerFactoryMock(final boolean statsEnabled) { EntityManagerFactory emf = Mockito.mock(EntityManagerFactory.class); SessionFactory sf = Mockito.mock(SessionFactory.class); Statistics stats = Mockito.mock(Statistics.class, invocation -> { if (invocation.getMethod().getName().equals("isStatisticsEnabled")) { return statsEnabled; } return 42L; }); when(emf.unwrap(SessionFactory.class)).thenReturn(sf); when(sf.getStatistics()).thenReturn(stats); return emf; }
protected void verifyQueryCount(final Statistics stats) { final long totalQueryCount = Math.max(stats.getQueryExecutionCount(), stats.getPrepareStatementCount()); if (assertions.maxQueries() >= 0 && totalQueryCount > assertions.maxQueries()) { final StringBuilder msgBuf = new StringBuilder(); msgBuf.append("Statements prepared: ").append(stats.getPrepareStatementCount()); // Create list of queries for debugging purposes final List<String> queryLines = Stream.of(stats.getQueries()) .map(query -> { final QueryStatistics qStats = stats.getQueryStatistics(query); return Tuple.of(qStats.getExecutionCount(), query); }) .sorted(reverseOrder()) .map(pair -> String.format("%s: %s", StringUtils.leftPad(pair._1.toString(), 3, ' '), pair._2)) .collect(toList()); if (!queryLines.isEmpty()) { msgBuf.append("\n Queries (ordered by execution count): ") .append(stats.getQueryExecutionCount()) .append("\n ") .append(Joiner.on("\n ").join(queryLines)); } throw new MaximumQueryCountExceededException(String.format("%s\n %s\n", MaximumQueryCountExceededException.getErrorMessage(assertions.maxQueries(), totalQueryCount), msgBuf.toString())); } if (assertions.queryCount() >= 0 && totalQueryCount != assertions.queryCount()) { throw new QueryCountAssertionException(assertions.queryCount(), totalQueryCount); } }
@Bean @DependsOn("statisticsService") public MBeanExporter jmxService(Statistics statistics) { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(ImmutableMap.of("Hibernate:application=Statistics", (Object) statistics)); return exporter; }
public void testSessionStats() throws Exception { SessionFactory sf = getSessions(); Statistics stats = sf.getStatistics(); boolean isStats = stats.isStatisticsEnabled(); stats.clear(); stats.setStatisticsEnabled(true); Session s = sf.openSession(); assertEquals( 1, stats.getSessionOpenCount() ); s.close(); assertEquals( 1, stats.getSessionCloseCount() ); s = sf.openSession(); Transaction tx = s.beginTransaction(); A a = new A(); a.setName("mya"); s.save(a); a.setName("b"); tx.commit(); s.close(); assertEquals( 1, stats.getFlushCount() ); s = sf.openSession(); tx = s.beginTransaction(); String hql = "from " + A.class.getName(); Query q = s.createQuery(hql); q.list(); tx.commit(); s.close(); assertEquals(1, stats.getQueryExecutionCount() ); assertEquals(1, stats.getQueryStatistics(hql).getExecutionCount() ); stats.setStatisticsEnabled(isStats); }
public void testSessionStatistics() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); Statistics stats = getSessions().getStatistics(); stats.clear(); boolean isStats = stats.isStatisticsEnabled(); stats.setStatisticsEnabled(true); Continent europe = fillDb(s); tx.commit(); s.clear(); tx = s.beginTransaction(); SessionStatistics sessionStats = s.getStatistics(); assertEquals( 0, sessionStats.getEntityKeys().size() ); assertEquals( 0, sessionStats.getEntityCount() ); assertEquals( 0, sessionStats.getCollectionKeys().size() ); assertEquals( 0, sessionStats.getCollectionCount() ); europe = (Continent) s.get( Continent.class, europe.getId() ); Hibernate.initialize( europe.getCountries() ); Hibernate.initialize( europe.getCountries().iterator().next() ); assertEquals( 2, sessionStats.getEntityKeys().size() ); assertEquals( 2, sessionStats.getEntityCount() ); assertEquals( 1, sessionStats.getCollectionKeys().size() ); assertEquals( 1, sessionStats.getCollectionCount() ); tx.commit(); s.close(); stats.setStatisticsEnabled( isStats); }
public void testEmptySecondLevelCacheEntry() throws Exception { getSessions().evictEntity( Item.class.getName() ); Statistics stats = getSessions().getStatistics(); stats.clear(); SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics( Item.class.getName() ); Map cacheEntries = statistics.getEntries(); assertEquals( 0, cacheEntries.size() ); }
private void scalabilityOnPopulate(String pattern, String teamName, int nbApp, int nbReleasePerApp, int nbEnvPerRelease) throws BusinessException, MalformedURLException { // Set reference values Map<HibernateStatsReferenceType, Long> refs = new HashMap<HibernateStatsReferenceType, Long>(14); refs.put(HibernateStatsReferenceType.DURATION, Long.valueOf(3600000)); refs.put(HibernateStatsReferenceType.QUERY_COUNT, Long.valueOf(1152)); refs.put(HibernateStatsReferenceType.QUERY_MAX_TIME_MS, Long.valueOf(1700)); refs.put(HibernateStatsReferenceType.ENTITY_FETCH_COUNT, Long.valueOf(8016)); refs.put(HibernateStatsReferenceType.ENTITY_LOAD_COUNT, Long.valueOf(43968)); refs.put(HibernateStatsReferenceType.ENTITY_INSERT_COUNT, Long.valueOf(44455)); refs.put(HibernateStatsReferenceType.ENTITY_DELETE_COUNT, Long.valueOf(0)); refs.put(HibernateStatsReferenceType.ENTITY_UPDATE_COUNT, Long.valueOf(3480)); refs.put(HibernateStatsReferenceType.COLLECTION_FETCH_COUNT, Long.valueOf(16360)); refs.put(HibernateStatsReferenceType.COLLECTION_LOAD_COUNT, Long.valueOf(16982)); refs.put(HibernateStatsReferenceType.COLLECTION_RECREATE_COUNT, Long.valueOf(29000)); refs.put(HibernateStatsReferenceType.COLLECTION_REMOVE_COUNT, Long.valueOf(0)); refs.put(HibernateStatsReferenceType.COLLECTION_UPDATE_COUNT, Long.valueOf(75)); // Creation of all paas users, app, app release and env long startTime = System.currentTimeMillis(); manageScalability.populate(pattern, teamName, nbApp, nbReleasePerApp, nbEnvPerRelease); long duration = System.currentTimeMillis() - startTime; Statistics stats = sessionFactory.getStatistics(); logger.info("Test duration : " + duration); StatisticsHelper.logStats(stats); // Check stats // Durations are not ignored as checking durations tends to make this test fragile due to IaaS and DBaaS response time dependencies HibernateStatsHelper.checkStatsIgnoringDuration(refs, stats); }
@Test public void checkFetchJoin() { Statistics statistics = sessionFactory.getStatistics(); statistics.setStatisticsEnabled(true); DataTablesOutput<A> output = getOutput(input); assertThat(output.getRecordsFiltered()).isEqualTo(3); assertThat(statistics.getPrepareStatementCount()).isEqualTo(2); assertThat(statistics.getEntityLoadCount()).isEqualTo(3 /* A */ + 3 /* C */); }
private Optional<Statistics> getHibernateStatistics() { try { return Optional.ofNullable(sessionFactory.getStatistics()); } catch (PersistenceException e) { logger.error("Cannot get statistics", e); return Optional.empty(); } }
public StatisticsDto(Statistics statistics) { this.closeStatementCount = statistics.getCloseStatementCount(); this.collectionFetchCount = statistics.getCollectionFetchCount(); this.collectionLoadCount = statistics.getCollectionLoadCount(); this.collectionRecreateCount = statistics.getCollectionRecreateCount(); this.collectionRemoveCount = statistics.getCollectionRemoveCount(); this.collectionUpdateCount = statistics.getCollectionUpdateCount(); this.connectCount = statistics.getConnectCount(); this.entityDeleteCount = statistics.getEntityDeleteCount(); this.entityFetchCount = statistics.getEntityFetchCount(); this.entityInsertCount = statistics.getEntityInsertCount(); this.entityLoadCount = statistics.getEntityLoadCount(); this.entityUpdateCount = statistics.getEntityUpdateCount(); this.flushCount = statistics.getFlushCount(); this.optimisticFailureCount = statistics.getOptimisticFailureCount(); this.prepareStatementCount = statistics.getPrepareStatementCount(); this.queryCacheHitCount = statistics.getQueryCacheHitCount(); this.queryCacheMissCount = statistics.getQueryCacheMissCount(); this.queryCachePutCount = statistics.getQueryCachePutCount(); this.queryExecutionCount = statistics.getQueryExecutionCount(); this.queryExecutionMaxTime = statistics.getQueryExecutionMaxTime(); this.secondLevelCacheHitCount = statistics.getSecondLevelCacheHitCount(); this.secondLevelCacheMissCount = statistics.getSecondLevelCacheMissCount(); this.secondLevelCachePutCount = statistics.getSecondLevelCachePutCount(); this.sessionCloseCount = statistics.getSessionCloseCount(); this.sessionOpenCount = statistics.getSessionOpenCount(); this.startTime = statistics.getStartTime(); this.successfulTransactionCount = statistics.getSuccessfulTransactionCount(); this.transactionCount = statistics.getTransactionCount(); }
/** * Get BoneCP stats */ public static com.jolbox.bonecp.Statistics getBoneCPStatistics() { BoneCPDataSource boneCPdatasource = (BoneCPDataSource) DB.getDataSource(); try { Field field = boneCPdatasource.getClass().getDeclaredField("pool"); field.setAccessible(true); BoneCP boneCP = (BoneCP) field.get(boneCPdatasource); return boneCP.getStatistics(); } catch (Exception e) { Logger.error(e.toString(), e); } return null; }
@Test @Ignore public void should_implement_all_public_methods() { Method[] delegatePublicMethods = Statistics.class.getMethods(); Method[] publicMethods = HibernateStatistics.class.getMethods(); List<Method> otherMethods = Arrays.stream(delegatePublicMethods) .filter(method -> !hasElement(publicMethods, method.getName())) .collect(Collectors.toList()); assertThat(otherMethods).isEmpty(); }
@Before public void setup() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); statistics = mock(Statistics.class); when(sessionFactory.getStatistics()).thenReturn(statistics); hibernateStatisticsSupport = new HibernateStatisticsSupport(sessionFactory); beanName = new ObjectName("fr.sewatech:type=HibernateStatistics"); }
public static EntityManager getEntityManager() throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException { if (emf == null) { emf = Persistence.createEntityManagerFactory( Util.getConfig().getString("bard.jpa.unit", "prod") ); final SessionFactory sessionFactory = ((HibernateEntityManagerFactory) emf).getSessionFactory(); ObjectName statsName = new ObjectName("org.hibernate:type=statistics"); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); final Statistics statistics = sessionFactory.getStatistics(); statistics.setStatisticsEnabled(true); Object statisticsMBean = Proxy.newProxyInstance(DBManager.class.getClassLoader(), new Class<?>[] {StatisticsMXBean.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(statistics, args); } }); mbeanServer.registerMBean(statisticsMBean, statsName); } return emf.createEntityManager(); }
@Before public void before() { registry = new CollectorRegistry(); sessionFactory = mock(SessionFactory.class); statistics = mock(Statistics.class); when(sessionFactory.getStatistics()).thenReturn(statistics); }
public void destroy() { System.err.println("destroying pm! " + pm); Statistics stats = factory.getStatistics(); stats.logSummary(); factory.close(); //session = null; }
private boolean hasStatisticsEnabled(EntityManagerFactory emf) { final Statistics stats = getStatistics(emf); return (stats != null && stats.isStatisticsEnabled()); }
/** * 此处需要进行封装,如果sessionFactory没有构建成功,就自己新建. 否则应该使用<code>sessionFactory.getStatistics()</code> */ public Statistics getStatistics() { return new StatisticsWrapper(); }
public Statistics getStatistics() { return getStatisticsImplementor(); }
public Statistics getStatistics() { return delegate.getStatistics(); }
public void verifyAndClear() { final Statistics stats = getStatistics(); verifyQueryCount(stats); stats.clear(); }
@Override protected Statistics getStatistics() { return sessionFactory().getStatistics(); }
protected Statistics getHibernateStatistics() { return sessionFactory().getStatistics(); }
public Statistics getStatistics() { return sessionFactory.getStatistics(); }
public Statistics getStatistics() { return delegateSessionFactory.getStatistics(); }
public void testQuery() throws Exception { final int entityCount = 10; final int queryCount = 3; insertDummyEntities(entityCount); // After inserting the entities, we need a slight delay. Otherwise, when the queries run, it's possible // that the UpdateTimestampsCache entry for DummyEntity still matches the current timestamp. When that // happens, this test fails because the StandardQueryCache considers the cached data out-of-date, which // results in an extra miss and put in the statistics. By delaying slightly here, we can be certain our // queries will have newer timestamps then tha cache does sleep(1); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); } Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { session.delete(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); assertEquals(1, stats.getQueryCachePutCount()); assertEquals(1, stats.getQueryCacheMissCount()); assertEquals(queryCount - 1, stats.getQueryCacheHitCount()); assertEquals(1, stats.getQueryExecutionCount()); assertEquals(entityCount, stats.getEntityInsertCount()); // FIXME // HazelcastRegionFactory puts into L2 cache 2 times; 1 on insert, 1 on query execution // assertEquals(entityCount, stats.getSecondLevelCachePutCount()); assertEquals(entityCount, stats.getEntityLoadCount()); assertEquals(entityCount, stats.getEntityDeleteCount()); assertEquals(entityCount * (queryCount - 1) * 2, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(entityCount, stats.getSecondLevelCacheMissCount()); stats.logSummary(); }
@Bean @DependsOn("entityManagerFactory") public Statistics statisticsService(EntityManagerFactory entityManagerFactory) { SessionFactory sf = ((HibernateEntityManagerFactory) entityManagerFactory).getSessionFactory(); return sf.getStatistics(); }
@Test public void testQuery() { final int entityCount = 10; final int queryCount = 3; insertDummyEntities(entityCount); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); } assertNotNull(list); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { session.delete(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); assertEquals(1, stats.getQueryCachePutCount()); assertEquals(1, stats.getQueryCacheMissCount()); assertEquals(queryCount - 1, stats.getQueryCacheHitCount()); assertEquals(1, stats.getQueryExecutionCount()); assertEquals(entityCount, stats.getEntityInsertCount()); // FIXME // HazelcastRegionFactory puts into L2 cache 2 times; 1 on insert, 1 on query execution // assertEquals(entityCount, stats.getSecondLevelCachePutCount()); assertEquals(entityCount, stats.getEntityLoadCount()); assertEquals(entityCount, stats.getEntityDeleteCount()); assertEquals(entityCount * (queryCount - 1) * 2, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(entityCount, stats.getSecondLevelCacheMissCount()); stats.logSummary(); }
@Test public void testQuery() { final int entityCount = 10; final int queryCount = 3; insertDummyEntities(entityCount); List<DummyEntity> list = null; for (int i = 0; i < queryCount; i++) { list = executeQuery(sf); assertEquals(entityCount, list.size()); sleepAtLeastSeconds(1); } assertNotNull(list); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); try { for (DummyEntity dummy : list) { session.delete(dummy); } tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } Statistics stats = sf.getStatistics(); assertEquals(1, stats.getQueryCachePutCount()); assertEquals(1, stats.getQueryCacheMissCount()); assertEquals(queryCount - 1, stats.getQueryCacheHitCount()); assertEquals(1, stats.getQueryExecutionCount()); assertEquals(entityCount, stats.getEntityInsertCount()); // FIXME // HazelcastRegionFactory puts into L2 cache 2 times; 1 on insert, 1 on query execution // assertEquals(entityCount, stats.getSecondLevelCachePutCount()); assertEquals(entityCount, stats.getEntityLoadCount()); assertEquals(entityCount, stats.getEntityDeleteCount()); assertEquals(entityCount * (queryCount - 1) * 2, stats.getSecondLevelCacheHitCount()); // collection cache miss assertEquals(entityCount, stats.getSecondLevelCacheMissCount()); stats.logSummary(); }