Java Code Examples for org.hibernate.stat.Statistics#isStatisticsEnabled()

The following examples show how to use org.hibernate.stat.Statistics#isStatisticsEnabled() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HibernateMetrics.java    From micrometer with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@code HibernateMetrics}.
 * @param entityManagerFactory entity manager factory to use
 * @param entityManagerFactoryName entity manager factory name as a tag value
 * @param tags additional tags
 * @deprecated since 1.1.2 in favor of {@link #HibernateMetrics(SessionFactory, String, Iterable)}
 */
@Deprecated
public HibernateMetrics(EntityManagerFactory entityManagerFactory, String entityManagerFactoryName, Iterable<Tag> tags) {
    this.tags = Tags.concat(tags, SESSION_FACTORY_TAG_NAME, entityManagerFactoryName);
    SessionFactory sessionFactory = unwrap(entityManagerFactory);
    if (sessionFactory != null) {
        Statistics statistics = sessionFactory.getStatistics();
        this.statistics = statistics.isStatisticsEnabled() ? statistics : null;
    } else {
        this.statistics = null;
    }
}
 
Example 2
Source File: StatisticsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
}
 
Example 3
Source File: SessionStatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);

}
 
Example 4
Source File: HibernateStatsUtils.java    From pnc with Apache License 2.0 4 votes vote down vote up
/**
 * Get all the Hibernate Entities statistics aggregated in a sorted Map
 * 
 * @param statistics
 * @return a sorted map containing all the Hibernate entities stats
 */
public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheEntitiesStats(
        Statistics statistics) {

    SortedMap<String, Map<String, HibernateMetric>> entitiesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

    if (statistics.isStatisticsEnabled()) {
        String[] entityNames = statistics.getEntityNames();
        Stream.of(entityNames).forEach(eN -> {
            EntityStatistics entityStat = statistics.getEntityStatistics(eN);
            SortedMap<String, HibernateMetric> entityStatMap = new TreeMap<String, HibernateMetric>();

            // Entity cache stats
            entityStatMap.put(
                    "cache.region.name",
                    createHibernateMetricItem(
                            "cacheRegionName",
                            "The name of the region where this data is cached.",
                            entityStat.getCacheRegionName()));
            entityStatMap.put(
                    "cache.hit.count",
                    createHibernateMetricItem(
                            "cacheHitCount",
                            "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            entityStat.getCacheHitCount()));
            entityStatMap.put(
                    "cache.miss.count",
                    createHibernateMetricItem(
                            "cacheMissCount",
                            "The number of unsuccessful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            entityStat.getCacheMissCount()));
            entityStatMap.put(
                    "cache.put.count",
                    createHibernateMetricItem(
                            "cachePutCount",
                            "The number of times this data has been into its configured cache region since the last Statistics clearing.",
                            entityStat.getCachePutCount()));
            double hitsRatio = (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) != 0
                    ? ((double) entityStat.getCacheHitCount()
                            / (entityStat.getCacheHitCount() + entityStat.getCacheMissCount()) * 100)
                    : -1;
            entityStatMap.put(
                    "cache.hit.ratio",
                    createHibernateMetricItem(
                            "cacheHitRatio",
                            "The ratio of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            df2.format(hitsRatio)));

            // Entity stats
            entityStatMap.put(
                    "fetch.count",
                    createHibernateMetricItem(
                            "fetchCount",
                            "Number of times (since last Statistics clearing) this entity has been fetched.",
                            entityStat.getFetchCount()));
            entityStatMap.put(
                    "insert.count",
                    createHibernateMetricItem(
                            "insertCount",
                            "Number of times (since last Statistics clearing) this entity has been inserted.",
                            entityStat.getInsertCount()));
            entityStatMap.put(
                    "delete.count",
                    createHibernateMetricItem(
                            "deleteCount",
                            "Number of times (since last Statistics clearing) this entity has been deleted.",
                            entityStat.getDeleteCount()));
            entityStatMap.put(
                    "load.count",
                    createHibernateMetricItem(
                            "loadCount",
                            "Number of times (since last Statistics clearing) this entity has been loaded.",
                            entityStat.getLoadCount()));
            entityStatMap.put(
                    "optimistic.failure.count",
                    createHibernateMetricItem(
                            "optimisticFailureCount",
                            "Number of times (since last Statistics clearing) this entity has experienced an optimistic lock failure.",
                            entityStat.getOptimisticFailureCount()));
            entityStatMap.put(
                    "update.count",
                    createHibernateMetricItem(
                            "updateCount",
                            "Number of times (since last Statistics clearing) this entity has been updated.",
                            entityStat.getUpdateCount()));

            entitiesStatMap.put(ENTITY_STATS_PREFIX + eN, entityStatMap);
        });
    }

    return entitiesStatMap;
}
 
Example 5
Source File: HibernateStatsUtils.java    From pnc with Apache License 2.0 4 votes vote down vote up
/**
 * Get all the Hibernate Entities second level cache statistics aggregated in a sorted Map
 * 
 * @param statistics
 * @return a sorted map containing all the Hibernate second level cache statistics
 */
public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheRegionsStats(
        Statistics statistics) {

    SortedMap<String, Map<String, HibernateMetric>> secondLevelCachesStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

    if (statistics.isStatisticsEnabled()) {
        String[] cacheRegionNames = statistics.getSecondLevelCacheRegionNames();
        Stream.of(cacheRegionNames).forEach(crN -> {
            try {
                CacheRegionStatistics sLCStats = statistics.getDomainDataRegionStatistics(crN);
                SortedMap<String, HibernateMetric> sLCStatMap = new TreeMap<String, HibernateMetric>();

                sLCStatMap.put(
                        "second-level-cache.cache.region.name",
                        createHibernateMetricItem(
                                "regionName",
                                "The name of the region where this data is cached.",
                                sLCStats.getRegionName()));

                sLCStatMap.put(
                        "second-level-cache.element.count.in.memory",
                        createHibernateMetricItem(
                                "elementCountInMemory",
                                "The number of elements currently in memory within the cache provider.",
                                sLCStats.getElementCountInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                        ? sLCStats.getElementCountInMemory()
                                        : -1));
                sLCStatMap.put(
                        "second-level-cache.element.count.on.disk",
                        createHibernateMetricItem(
                                "elementCountOnDisk",
                                "The number of elements currently stored to disk within the cache provider.",
                                sLCStats.getElementCountOnDisk() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                        ? sLCStats.getElementCountOnDisk()
                                        : -1));
                sLCStatMap.put(
                        "second-level-cache.size.in.memory",
                        createHibernateMetricItem(
                                "sizeInMemory",
                                "The size that the in-memory elements take up within the cache provider.",
                                sLCStats.getSizeInMemory() != CacheRegionStatistics.NO_EXTENDED_STAT_SUPPORT_RETURN
                                        ? sLCStats.getSizeInMemory()
                                        : -1));

                sLCStatMap.put(
                        "second-level-cache.hit.count",
                        createHibernateMetricItem(
                                "hitCount",
                                "The number of successful cache look-ups against the region since the last Statistics clearing.",
                                sLCStats.getHitCount()));
                sLCStatMap.put(
                        "second-level-cache.miss.count",
                        createHibernateMetricItem(
                                "missCount",
                                "The number of unsuccessful cache look-ups against the region since the last Statistics clearing.",
                                sLCStats.getMissCount()));
                double secondLvlCacheHitsRatio = (sLCStats.getHitCount() + sLCStats.getMissCount()) != 0
                        ? ((double) sLCStats.getHitCount() / (sLCStats.getHitCount() + sLCStats.getMissCount())
                                * 100)
                        : -1;
                sLCStatMap.put(
                        "second-level-cache.hit.ratio",
                        createHibernateMetricItem(
                                "hitRatio",
                                "The ratio of successful cache look-ups against the region since the last Statistics clearing.",
                                df2.format(secondLvlCacheHitsRatio)));
                sLCStatMap.put(
                        "second-level-cache.put.count",
                        createHibernateMetricItem(
                                "putCount",
                                "The number of cache puts into the region since the last Statistics clearing.",
                                sLCStats.getPutCount()));

                secondLevelCachesStatMap.put(REGION_STATS_PREFIX + crN, sLCStatMap);
            } catch (IllegalArgumentException e) {
                // logger.error("The region name could not be resolved: {}", e);
            }
        });
    }

    return secondLevelCachesStatMap;
}
 
Example 6
Source File: HibernateStatsUtils.java    From pnc with Apache License 2.0 4 votes vote down vote up
/**
 * Get all the Hibernate collections statistics aggregated in a sorted Map
 * 
 * @param statistics
 * @return a sorted map containing all the Hibernate collections statistics
 */
public static SortedMap<String, Map<String, HibernateMetric>> getSecondLevelCacheCollectionsStats(
        Statistics statistics) {

    SortedMap<String, Map<String, HibernateMetric>> collectionsStatMap = new TreeMap<String, Map<String, HibernateMetric>>();

    if (statistics.isStatisticsEnabled()) {
        String[] collectionRoleNames = statistics.getCollectionRoleNames();
        Stream.of(collectionRoleNames).forEach(crN -> {
            CollectionStatistics cStats = statistics.getCollectionStatistics(crN);
            SortedMap<String, HibernateMetric> cStatMap = new TreeMap<String, HibernateMetric>();

            // Collection cache stats
            cStatMap.put(
                    "cache.region.name",
                    createHibernateMetricItem(
                            "cacheRegionName",
                            "The name of the region where this data is cached.",
                            cStats.getCacheRegionName()));

            cStatMap.put(
                    "cache.hit.count",
                    createHibernateMetricItem(
                            "cacheHitCount",
                            "The number of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            cStats.getCacheHitCount()));
            cStatMap.put(
                    "cache.miss.count",
                    createHibernateMetricItem(
                            "cacheMissCount",
                            "The number of unsuccessful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            cStats.getCacheMissCount()));
            double secondLvlCacheHitsRatio = (cStats.getCacheHitCount() + cStats.getCacheMissCount()) != 0
                    ? ((double) cStats.getCacheHitCount() / (cStats.getCacheHitCount() + cStats.getCacheMissCount())
                            * 100)
                    : -1;
            cStatMap.put(
                    "cache.hit.ratio",
                    createHibernateMetricItem(
                            "cacheHitRatio",
                            "The ratio of successful cache look-ups for this data from its configured cache region since the last Statistics clearing.",
                            df2.format(secondLvlCacheHitsRatio)));
            cStatMap.put(
                    "cache.put.count",
                    createHibernateMetricItem(
                            "cachePutCount",
                            "The number of times this data has been into its configured cache region since the last Statistics clearing.",
                            cStats.getCachePutCount()));

            // Collection stats
            cStatMap.put(
                    "fetch.count",
                    createHibernateMetricItem(
                            "fetchCount",
                            "Number of times (since last Statistics clearing) this collection has been fetched.",
                            cStats.getFetchCount()));
            cStatMap.put(
                    "recreate.count",
                    createHibernateMetricItem(
                            "recreateCount",
                            "Number of times (since last Statistics clearing) this collection has been recreated (rows potentially deleted and then rows (re-)inserted).",
                            cStats.getRecreateCount()));
            cStatMap.put(
                    "remove.count",
                    createHibernateMetricItem(
                            "removeCount",
                            "Number of times (since last Statistics clearing) this collection has been removed.",
                            cStats.getRemoveCount()));
            cStatMap.put(
                    "load.count",
                    createHibernateMetricItem(
                            "loadCount",
                            "Number of times (since last Statistics clearing) this collection has been loaded.",
                            cStats.getLoadCount()));
            cStatMap.put(
                    "update.count",
                    createHibernateMetricItem(
                            "updateCount",
                            "Number of times (since last Statistics clearing) this collection has been updated.",
                            cStats.getUpdateCount()));

            collectionsStatMap.put(COLLECTION_STATS_PREFIX + crN, cStatMap);
        });
    }

    return collectionsStatMap;
}
 
Example 7
Source File: HibernateInformationProvider.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, Object> asJson() {
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    Statistics statistics = sessionFactory.getStatistics();
    if (!statistics.isStatisticsEnabled()){
        return json;
    }
    json.put("EntityDeleteCount", statistics.getEntityDeleteCount());
    json.put("EntityInsertCount", statistics.getEntityInsertCount());
    json.put("EntityLoadCount", statistics.getEntityLoadCount());
    json.put("EntityFetchCount", statistics.getEntityFetchCount());
    json.put("EntityUpdateCount", statistics.getEntityUpdateCount());
    json.put("QueryExecutionCount", statistics.getQueryExecutionCount());
    json.put("QueryExecutionMaxTime", statistics.getQueryExecutionMaxTime());
    json.put("QueryExecutionMaxTimeQueryString", statistics.getQueryExecutionMaxTimeQueryString());
    json.put("QueryCacheHitCount", statistics.getQueryCacheHitCount());
    json.put("QueryCacheMissCount", statistics.getQueryCacheMissCount());
    json.put("QueryCachePutCount", statistics.getQueryCachePutCount());
    json.put("FlushCount", statistics.getFlushCount());
    json.put("ConnectCount", statistics.getConnectCount());
    json.put("SecondLevelCacheHitCount", statistics.getSecondLevelCacheHitCount());
    json.put("SecondLevelCacheMissCount", statistics.getSecondLevelCacheMissCount());
    json.put("SecondLevelCachePutCount", statistics.getSecondLevelCachePutCount());
    json.put("SessionCloseCount", statistics.getSessionCloseCount());
    json.put("SessionOpenCount", statistics.getSessionOpenCount());
    json.put("CollectionLoadCount", statistics.getCollectionLoadCount());
    json.put("CollectionFetchCount", statistics.getCollectionFetchCount());
    json.put("CollectionUpdateCount", statistics.getCollectionUpdateCount());
    json.put("CollectionRemoveCount", statistics.getCollectionRemoveCount());
    json.put("CollectionRecreateCount", statistics.getCollectionRecreateCount());
    json.put("StartTime", statistics.getStartTime());
    json.put("SecondLevelCacheRegionNames", statistics.getSecondLevelCacheRegionNames());
    json.put("SuccessfulTransactionCount", statistics.getSuccessfulTransactionCount());
    json.put("TransactionCount", statistics.getTransactionCount());
    json.put("PrepareStatementCount", statistics.getPrepareStatementCount());
    json.put("CloseStatementCount", statistics.getCloseStatementCount());
    json.put("OptimisticFailureCount", statistics.getOptimisticFailureCount());

    LinkedHashMap<String, Object> queryStats = new LinkedHashMap<>();
    json.put("Queries", queryStats);

    String[] queries = statistics.getQueries();
    for (String query : queries) {
        queryStats.put(query, statistics.getQueryStatistics(query));
    }

    LinkedHashMap<String, Object> entityStatistics = new LinkedHashMap<>();
    json.put("EntityStatistics", entityStatistics);

    String[] entityNames = statistics.getEntityNames();
    for (String entityName : entityNames) {
        entityStatistics.put(entityName, statistics.getEntityStatistics(entityName));
    }

    LinkedHashMap<String, Object> roleStatistics = new LinkedHashMap<>();
    json.put("RoleStatistics", roleStatistics);

    String[] roleNames = statistics.getCollectionRoleNames();
    for (String roleName : roleNames) {
        roleStatistics.put(roleName, statistics.getCollectionStatistics(roleName));
    }

    return json;
}
 
Example 8
Source File: HibernateMetrics.java    From micrometer with Apache License 2.0 2 votes vote down vote up
/**
 * Create a {@code HibernateMetrics}.
 * @param sessionFactory session factory to use
 * @param sessionFactoryName session factory name as a tag value
 * @param tags additional tags
 */
public HibernateMetrics(SessionFactory sessionFactory, String sessionFactoryName, Iterable<Tag> tags) {
    this.tags = Tags.concat(tags, SESSION_FACTORY_TAG_NAME, sessionFactoryName);
    Statistics statistics = sessionFactory.getStatistics();
    this.statistics = statistics.isStatisticsEnabled() ? statistics : null;
}