下面列出了org.hibernate.stat.Statistics#clear ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
@Test
public void testInQueryCachePlan() {
SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
Statistics statistics = sessionFactory.getStatistics();
statistics.clear();
doInJPA(entityManager -> {
for (int i = 1; i < 16; i++) {
getPostByIds(
entityManager,
IntStream.range(1, i + 1).boxed().toArray(Integer[]::new)
);
}
});
assertEquals(16L, statistics.getQueryPlanCacheMissCount());
for (String query : statistics.getQueries()) {
LOGGER.info("Executed query: {}", query);
}
}
@Test
public void testJPQL() {
SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
Statistics statistics = sessionFactory.getStatistics();
statistics.clear();
doInJPA(entityManager -> {
List<Post> posts = entityManager.createQuery(
"select p " +
"from Post p " +
"where p.id in :ids", Post.class)
.setParameter("ids", Arrays.asList(1, 2, 3))
.getResultList();
});
for (String query : statistics.getQueries()) {
LOGGER.info("Executed query: {}", query);
}
}
@Test
public void testCriteriaAPI() {
SessionFactory sessionFactory = entityManagerFactory().unwrap(SessionFactory.class);
Statistics statistics = sessionFactory.getStatistics();
statistics.clear();
doInJPA(entityManager -> {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Post> criteria = builder.createQuery(Post.class);
Root<Post> fromPost = criteria.from(Post.class);
criteria.where(builder.in(fromPost.get("id")).value(Arrays.asList(1, 2, 3)));
List<Post> posts = entityManager.createQuery(criteria).getResultList();
});
for (String query : statistics.getQueries()) {
LOGGER.info("Executed query: {}", query);
}
}
@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);
}
});
}
private void testOneToOneUniDirectional(boolean relationship) {
int n = 10;
ResourceRepository<OneToOneTestEntity, Serializable> testRepo = client.getRepositoryForType(OneToOneTestEntity.class);
ResourceRepository<RelatedEntity, Serializable> otherRepo = client.getRepositoryForType(RelatedEntity.class);
RelationshipRepository relRepo = client.getRepositoryForType(OneToOneTestEntity.class, RelatedEntity.class);
for (int i = 0; i < n; i++) {
RelatedEntity related = new RelatedEntity();
related.setId(12L + i);
otherRepo.create(related);
OneToOneTestEntity test = new OneToOneTestEntity();
test.setId(11L + i);
if (!relationship) {
test.setOneRelatedValue(related);
}
testRepo.create(test);
if (relationship) {
relRepo.setRelation(test, related.getId(), "oneRelatedValue");
}
}
Statistics stats = sessionFactory.getStatistics();
stats.clear();
QuerySpec querySpec = new QuerySpec(OneToOneTestEntity.class);
querySpec.includeRelation(Arrays.asList("oneRelatedValue"));
ResourceList<OneToOneTestEntity> list = testRepo.findAll(querySpec);
Assert.assertEquals(10, list.size());
OneToOneTestEntity testCopy = list.get(0);
Assert.assertNotNull(testCopy.getOneRelatedValue());
Assert.assertEquals(12L, testCopy.getOneRelatedValue().getId().longValue());
// verify no lazy loading and n+1 issues
Assert.assertEquals(0, stats.getEntityFetchCount());
Assert.assertEquals(2, stats.getQueryExecutionCount());
Assert.assertEquals(0, stats.getCollectionFetchCount());
}
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() );
}
@Override
public void run(KeycloakSession session) {
SessionFactory sessionFactory = ((SessionFactoryImpl) emf);
Statistics stats = sessionFactory.getStatistics();
logStats(stats);
stats.clear(); // For now, clear stats after each iteration
}
private static Statistics getStatistics(final EntityManagerFactory emf) {
final Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
stats.clear();
return stats;
}
public void testJoinedSubclass() {
if ( ! supportsCircularCascadeDelete() ) {
return;
}
Statistics statistics = getSessions().getStatistics();
statistics.clear();
Session s = openSession();
Transaction t = s.beginTransaction();
Salesperson mark = new Salesperson();
mark.setName("Mark");
mark.setTitle("internal sales");
mark.setSex('M');
mark.setAddress("buckhead");
mark.setZip("30305");
mark.setCountry("USA");
Person joe = new Person();
joe.setName("Joe");
joe.setAddress("San Francisco");
joe.setZip("XXXXX");
joe.setCountry("USA");
joe.setSex('M');
joe.setSalesperson(mark);
mark.getCustomers().add(joe);
s.save(mark);
t.commit();
assertEquals( statistics.getEntityInsertCount(), 2 );
assertEquals( statistics.getPrepareStatementCount(), 5 );
statistics.clear();
t = s.beginTransaction();
s.delete(mark);
t.commit();
assertEquals( statistics.getEntityDeleteCount(), 2 );
if ( !(getDialect() instanceof MySQLDialect) || (getDialect() instanceof MySQLInnoDBDialect) ) {
assertEquals( statistics.getPrepareStatementCount(), 1 );
}
t = s.beginTransaction();
List names = s.createQuery("select name from Person").list();
assertTrue( names.isEmpty() );
t.commit();
s.close();
}
public void testCollectionFetchVsLoad() throws Exception {
Statistics stats = getSessions().getStatistics();
stats.clear();
Session s = openSession();
Transaction tx = s.beginTransaction();
Continent europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals(0, stats.getCollectionLoadCount() );
assertEquals(0, stats.getCollectionFetchCount() );
Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
europe2.getCountries().size();
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
stats.clear();
europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
europe2 = (Continent) s.createQuery(
"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
).uniqueResult();
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() );
tx.commit();
s.close();
Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.JOIN);
coll.setLazy(false);
SessionFactory sf = getCfg().buildSessionFactory();
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);
s = sf.openSession();
tx = s.beginTransaction();
europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() );
tx.commit();
s.close();
sf.close();
coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
coll.setFetchMode(FetchMode.SELECT);
coll.setLazy(false);
sf = getCfg().buildSessionFactory();
stats = sf.getStatistics();
stats.clear();
stats.setStatisticsEnabled(true);
s = sf.openSession();
tx = s.beginTransaction();
europe = fillDb(s);
tx.commit();
s.clear();
tx = s.beginTransaction();
assertEquals( 0, stats.getCollectionLoadCount() );
assertEquals( 0, stats.getCollectionFetchCount() );
europe2 = (Continent) s.get( Continent.class, europe.getId() );
assertEquals( 1, stats.getCollectionLoadCount() );
assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() );
Iterator countries = europe2.getCountries().iterator();
while ( countries.hasNext() ) {
s.delete( countries.next() );
}
cleanDb( s );
tx.commit();
s.close();
}
public void testQueryStatGathering() {
Statistics stats = getSessions().getStatistics();
stats.clear();
Session s = openSession();
Transaction tx = s.beginTransaction();
fillDb(s);
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
final String continents = "from Continent";
int results = s.createQuery( continents ).list().size();
QueryStatistics continentStats = stats.getQueryStatistics( continents );
assertNotNull( "stats were null", continentStats );
assertEquals( "unexpected execution count", 1, continentStats.getExecutionCount() );
assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
long maxTime = continentStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
// assertEquals( continents, stats.getQueryExecutionMaxTimeQueryString() );
Iterator itr = s.createQuery( continents ).iterate();
// iterate() should increment the execution count
assertEquals( "unexpected execution count", 2, continentStats.getExecutionCount() );
// but should not effect the cumulative row count
assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
Hibernate.close( itr );
ScrollableResults scrollableResults = s.createQuery( continents ).scroll();
// same deal with scroll()...
assertEquals( "unexpected execution count", 3, continentStats.getExecutionCount() );
assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
scrollableResults.close();
tx.commit();
s.close();
// explicitly check that statistics for "split queries" get collected
// under the original query
stats.clear();
s = openSession();
tx = s.beginTransaction();
final String localities = "from Locality";
results = s.createQuery( localities ).list().size();
QueryStatistics localityStats = stats.getQueryStatistics( localities );
assertNotNull( "stats were null", localityStats );
// ...one for each split query
assertEquals( "unexpected execution count", 2, localityStats.getExecutionCount() );
assertEquals( "unexpected row count", results, localityStats.getExecutionRowCount() );
maxTime = localityStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
// assertEquals( localities, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
assertFalse( s.isOpen() );
// native sql queries
stats.clear();
s = openSession();
tx = s.beginTransaction();
final String sql = "select id, name from Country";
results = s.createSQLQuery( sql ).addEntity( Country.class ).list().size();
QueryStatistics sqlStats = stats.getQueryStatistics( sql );
assertNotNull( "sql stats were null", sqlStats );
assertEquals( "unexpected execution count", 1, sqlStats.getExecutionCount() );
assertEquals( "unexpected row count", results, sqlStats.getExecutionRowCount() );
maxTime = sqlStats.getExecutionMaxTime();
assertEquals( maxTime, stats.getQueryExecutionMaxTime() );
// assertEquals( sql, stats.getQueryExecutionMaxTimeQueryString() );
tx.commit();
s.close();
s = openSession();
tx = s.beginTransaction();
cleanDb( s );
tx.commit();
s.close();
}