下面列出了怎么用org.hibernate.stat.Statistics的API类实例代码及写法,或者点击链接到github查看源代码。
private static Statistics verifyFindCountryByNaturalId(EntityManagerFactory emf, String callingCode, String expectedName) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Session session = em.unwrap(Session.class);
final NaturalIdLoadAccess<Country> loader = session.byNaturalId(Country.class);
loader.using("callingCode", callingCode);
Country country = loader.load();
if (!country.getName().equals(expectedName))
throw new RuntimeException("Incorrect citizen: " + country.getName() + ", expected: " + expectedName);
transaction.commit();
em.close();
return stats;
}
private static void updateNaturalId(EntityManagerFactory emf, Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Session session = em.unwrap(Session.class);
final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
loader.using("ssn", "45989213T");
Citizen citizen = loader.load();
String expected = "Stark";
if (!citizen.getLastname().equals(expected))
throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expected);
citizen.setSsn("78902007R");
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
private static void verifyFindCitizenByNaturalId(EntityManagerFactory emf, String ssn, String expectedLastName,
Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Session session = em.unwrap(Session.class);
final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
loader.using("ssn", ssn);
Citizen citizen = loader.load();
if (!citizen.getLastname().equals(expectedLastName))
throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expectedLastName);
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
private static void storeTestPokemonTrainers(final EntityManagerFactory emf, Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Pokemon rocky = new Pokemon(68, "Rocky", 3056);
final Pokemon sonGoku = new Pokemon(149, "Son Goku", 3792);
final Pokemon mmMan = new Pokemon(94, "Marshmallow Man", 2842);
em.persist(rocky);
em.persist(sonGoku);
em.persist(mmMan);
em.persist(new Trainer(rocky, sonGoku, mmMan));
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
private static void verifyReadWriteCollection(final EntityManagerFactory emf, int expectedSize,
Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Trainer t1 = em.find(Trainer.class, 1L);
final List<Pokemon> pokemons = t1.getPokemons();
if (pokemons.size() != expectedSize)
throw new RuntimeException("Incorrect family size: " + pokemons.size() + ", expected: " + expectedSize);
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
private static void updateItemDescriptions(final EntityManagerFactory emf, String[] newValues, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Item i1 = em.find(Item.class, 1L);
i1.setDescription(newValues[0]);
final Item i2 = em.find(Item.class, 2L);
i2.setDescription(newValues[1]);
final Item i3 = em.find(Item.class, 3L);
i3.setDescription(newValues[2]);
transaction.commit();
em.close();
assertRegionStats(expected, Item.class.getName(), stats);
}
private static void rebalanceCpsForPokemons(final EntityManagerFactory emf, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Pokemon igeldo = em.find(Pokemon.class, 3);
igeldo.setCp(2707);
Pokemon godzilla = em.find(Pokemon.class, 248);
godzilla.setCp(3834);
Pokemon blissey = em.find(Pokemon.class, 242);
blissey.setCp(2757);
transaction.commit();
em.close();
assertRegionStats(expected, Pokemon.class.getName(), stats);
}
private static void storeTestPokemons(final EntityManagerFactory emf, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
final Pokemon igeldo = new Pokemon(3, "Venusaur", 2555);
em.persist(igeldo);
final Pokemon godzilla = new Pokemon(248, "Tyranitar", 3670);
em.persist(godzilla);
final Pokemon khaleesi = new Pokemon(242, "Blissey", 3219);
em.persist(khaleesi);
transaction.commit();
em.close();
assertRegionStats(expected, Pokemon.class.getName(), stats);
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
@Test
public void testIncludeManyRelations() {
addTestWithManyRelations(10);
Statistics stats = sessionFactory.getStatistics();
stats.clear();
QuerySpec querySpec = new QuerySpec(TestEntity.class);
querySpec.includeRelation(Arrays.asList(TestEntity.ATTR_manyRelatedValues));
List<TestEntity> list = testRepo.findAll(querySpec);
Assert.assertEquals(10, list.size());
TestEntity testEntity = list.get(0);
List<RelatedEntity> manyRelatedValues = testEntity.getManyRelatedValues();
Assert.assertNotNull(manyRelatedValues);
Assert.assertEquals(5, manyRelatedValues.size());
Assert.assertEquals(0, stats.getEntityFetchCount());
Assert.assertEquals(3, stats.getQueryExecutionCount());
// TODO issue with map eager loading:
// Assert.assertEquals(1, stats.getCollectionFetchCount());
}
@GET
@Path("/hibernate-cache/7")
@Produces("application/json")
public String step7_queryEntities() {
StringBuilder out = new StringBuilder();
// Query entities, expect:
// * no cache hits since query is not cached
// * a query cache miss and query cache put
ejb.queryEntities(out);
Statistics stats = getStatistics();
printfAssert("Query cache miss: %d (expected %d)%n", stats.getQueryCacheMissCount(), 1, out);
printfAssert("Query cache put: %d (expected %d)%n", stats.getQueryCachePutCount(), 1, out);
return out.toString();
}
@GET
@Path("/hibernate-cache/8")
@Produces("application/json")
public String step8_repeatQuery() {
StringBuilder out = new StringBuilder();
// Repeat query, expect:
// * two cache hits for the number of entities in cache
// * a query cache hit
ejb.queryEntities(out);
Statistics stats = getStatistics();
printfAssert("Event entity cache hits: %d (expected %d)%n", stats.getSecondLevelCacheHitCount(), 2, out);
printfAssert("Query cache hit: %d (expected %d)%n", stats.getQueryCacheHitCount(), 1, out);
return out.toString();
}
private void printSessionFactoryStats(Statistics statistics, String regionName) {
SortedMap<String, Map<String, HibernateMetric>> entitiesStatMap = getSecondLevelCacheEntitiesStats(statistics);
SortedMap<String, Map<String, HibernateMetric>> secondLevelCacheStatMap = getSecondLevelCacheRegionsStats(
statistics);
SortedMap<String, Map<String, HibernateMetric>> collectionStatMap = getSecondLevelCacheCollectionsStats(
statistics);
logger.debug("--- SECOND LEVEL STATS ---");
logger.debug("Entities stats of {}: {}", regionName, entitiesStatMap.get(ENTITY_STATS_PREFIX + regionName));
logger.debug(
"Collection stats of {} : {}",
regionName,
collectionStatMap.get(COLLECTION_STATS_PREFIX + regionName));
logger.debug(
"Second level cache stats of {}: {}",
regionName,
secondLevelCacheStatMap.get(REGION_STATS_PREFIX + regionName));
logger.debug("--- --- --- --- --- ---");
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.get(ItemTransactional.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
protected void logEntities(StringBuilder builder, String lineSep, Statistics stats) {
builder.append("Important entities statistics: ").append(lineSep);
for (String entity : stats.getEntityNames()) {
EntityStatistics entityStats = stats.getEntityStatistics(entity);
if (entityStats.getInsertCount() > LIMIT || entityStats.getDeleteCount() > LIMIT || entityStats.getUpdateCount() > LIMIT || entityStats.getLoadCount() > LIMIT || entityStats.getFetchCount() > LIMIT) {
builder.append(entity).append(" - ")
.append("inserted: ").append(entityStats.getInsertCount())
.append(", updated: ").append(entityStats.getUpdateCount())
.append(", removed: ").append(entityStats.getDeleteCount())
.append(", loaded: ").append(entityStats.getLoadCount())
.append(", fetched: ").append(entityStats.getFetchCount())
.append(lineSep);
}
}
builder.append(lineSep);
}
@Test
public void testInQueryCachePlan() {
SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
Statistics statistics = sessionFactory.getStatistics();
statistics.clear();
doInJPA(entityManager -> {
for (int i = 2; i < 16; i++) {
getPostByIds(
entityManager,
IntStream.range(1, i).boxed().toArray(Integer[]::new)
);
}
assertEquals(6L, statistics.getQueryPlanCacheMissCount());
for (String query : statistics.getQueries()) {
LOGGER.info("Executed query: {}", query);
}
});
}
@Test
public void testUpdateWithRefreshThenRollback() {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
item.setName("newdata");
s.update(item);
s.flush();
s.refresh(item);
s.getTransaction().rollback();
s.clear();
s.close();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
}
private static void storeTestCountries(final EntityManagerFactory emf, Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.persist(new Country("Spain", "+34"));
em.persist(new Country("Switzerland", "+41"));
em.persist(new Country("France", "+33"));
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
@Test
public void testNaturalId() {
Statistics stats = sessionFactory().getStatistics();
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional("data");
item.setNid("123");
s.save(item);
s.flush();
s.getTransaction().commit();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getPutCount());
Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemTransactional) s.bySimpleNaturalId(ItemTransactional.class).load("123");
assertThat(item).isNotNull();
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
Assert.assertEquals(1, stats.getNaturalIdCacheStatistics("item##NaturalId").getHitCount());
sessionFactory().getStatistics().logSummary();
}
private static void verifyFindByIdItems(final EntityManagerFactory emf, String[] expectedDesc, Counts expected) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
findByIdItems(em, expectedDesc);
transaction.commit();
em.close();
assertRegionStats(expected, Item.class.getName(), stats);
}
private static void testReadOnly(EntityManagerFactory entityManagerFactory) {
//Store some well known Person instances we can then test on:
storeTestPersons(entityManagerFactory, new Counts(4, 0, 0, 4));
//Load all persons and run some checks on the cache hits
Statistics beforeEvictStats = verifyFindByIdPersons(entityManagerFactory);
assertRegionStats(new Counts(0, 4, 0, 4), Person.class.getName(), beforeEvictStats);
}
private static Statistics verifyFindByIdPersons(final EntityManagerFactory emf) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
findByIdPersons(em);
transaction.commit();
em.close();
return stats;
}
private static void verifyListOfExistingPersons(final EntityManagerFactory emf, Map<String, Counts> counts) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
listExistingPersons(em);
transaction.commit();
em.close();
assertRegionStats(counts, stats);
}
@Test
public void testCollection() {
Long id = null;
Statistics stats = sessionFactory().getStatistics();
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite("data");
item.getEntries().addAll(Arrays.asList("a", "b", "c"));
id = (Long) s.save(item);
s.flush();
s.getTransaction().commit();
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
assertThat(item.getEntries()).containsExactly("a", "b", "c");
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getPutCount());
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
assertThat(item.getEntries()).containsExactly("a", "b", "c");
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item_entries").getHitCount());
}
private static void testDeleteViaRemove(final EntityManagerFactory emf) {
Statistics stats = getStatistics(emf);
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
em.remove(em.find(Pokemon.class, 3));
em.remove(em.find(Pokemon.class, 248));
em.remove(em.find(Pokemon.class, 242));
transaction.commit();
em.close();
assertRegionStats(new Counts(0, 3, 0, 4), Pokemon.class.getName(), stats);
stats = getStatistics(emf);
em = emf.createEntityManager();
transaction = em.getTransaction();
transaction.begin();
if (em.find(Pokemon.class, 3) != null
|| em.find(Pokemon.class, 248) != null
|| em.find(Pokemon.class, 242) != null) {
throw new RuntimeException("Pokemons should have been deleted");
}
transaction.commit();
em.close();
assertRegionStats(new Counts(0, 0, 3, 4), Pokemon.class.getName(), stats);
}
private static void assertRegionStats(Map<String, Counts> counts, Statistics stats) {
for (Map.Entry<String, Counts> entry : counts.entrySet()) {
final String region = entry.getKey();
final Counts expected = entry.getValue();
final Counts actual = statsToCounts(region, stats);
assertCountEquals(expected, actual, region);
}
}
@Test
public void testMappedSecondLevelCacheStats() {
Session session = (Session) em_1.getDelegate();
SessionFactory sessionFactory = session.getSessionFactory();
Statistics statistics = sessionFactory.getStatistics();
// Initialize sample build configurations, these cannot be done by DBUnit because of the Hibernate Envers
// Auditing
insertExampleBuildConfigurations(em_1, basicRepositoryConfiguration);
SortedMap<String, Map<String, HibernateMetric>> secondLevelCacheStatMap = getSecondLevelCacheRegionsStats(
statistics);
logger.debug("All second level cache stats: {}", secondLevelCacheStatMap);
String[] mappedEntities = {
// REGION_STATS_PREFIX + "org.jboss.pnc.model.Artifact",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigSetRecord",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigurationSet",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildEnvironment",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord",
REGION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecordPushResult",
REGION_STATS_PREFIX + "org.jboss.pnc.model.Product",
REGION_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestone",
REGION_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestoneRelease",
REGION_STATS_PREFIX + "org.jboss.pnc.model.ProductRelease",
REGION_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion",
REGION_STATS_PREFIX + "org.jboss.pnc.model.Project",
REGION_STATS_PREFIX + "org.jboss.pnc.model.RepositoryConfiguration",
REGION_STATS_PREFIX + "org.jboss.pnc.model.TargetRepository",
REGION_STATS_PREFIX + "org.jboss.pnc.model.User" };
Set<String> mappedEntitiesSet = new HashSet<String>(Arrays.asList(mappedEntities));
assertTrue(secondLevelCacheStatMap.keySet().containsAll(mappedEntitiesSet));
}
@Test
public void testTimeToLive() throws InterruptedException {
Statistics stats = sessionFactory().getStatistics();
Long id = null;
Session s = openSession();
s.beginTransaction();
ItemReadWrite item = new ItemReadWrite( "data" );
id = (Long) s.save( item );
s.flush();
s.getTransaction().commit();
s.close();
Thread.sleep(900);
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
Assert.assertEquals(0, stats.getSecondLevelCacheStatistics("item").getMissCount());
Thread.sleep(600);
s = openSession();
s.beginTransaction();
item = (ItemReadWrite) s.get(ItemReadWrite.class, id);
Assert.assertEquals("data", item.getName());
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getHitCount());
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("item").getMissCount());
}
@Test
public void testQuery() {
Statistics stats = sessionFactory().getStatistics();
Session s = openSession();
s.beginTransaction();
ItemTransactional item = new ItemTransactional("data");
item.getEntries().addAll(Arrays.asList("a", "b", "c"));
s.save(item);
s.flush();
s.getTransaction().commit();
s = openSession();
s.beginTransaction();
Query query = s.getNamedQuery("testQuery");
query.setCacheable(true);
query.setCacheRegion("myTestQuery");
query.setParameter("name", "data");
item = (ItemTransactional) query.uniqueResult();
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());
s = openSession();
s.beginTransaction();
Query query2 = s.getNamedQuery("testQuery");
query2.setCacheable(true);
query2.setCacheRegion("myTestQuery");
query2.setParameter("name", "data");
item = (ItemTransactional) query2.uniqueResult();
s.delete(item);
s.getTransaction().commit();
s.close();
Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
stats.logSummary();
}