Java Code Examples for org.hibernate.Session#getSessionFactory()

The following examples show how to use org.hibernate.Session#getSessionFactory() . 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: IgniteTestHelper.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public Map<String, Object> extractEntityTuple(Session session, EntityKey key) {
	SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) session.getSessionFactory();
	IgniteCache<Object, BinaryObject> cache = getEntityCache( sessionFactory, key.getMetadata() );
	Object cacheKey = getProvider( sessionFactory ).createKeyObject( key );

	Map<String, Object> result = new HashMap<>();
	BinaryObject po = cache.get( cacheKey );

	TupleSnapshot snapshot = new IgniteTupleSnapshot( cacheKey, po, key.getMetadata() );
	for ( String fieldName : snapshot.getColumnNames() ) {
		result.put( fieldName, snapshot.get( fieldName ) );
	}

	return result;
}
 
Example 2
Source File: DefaultSequenceHandlerRepository.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public Long getNextID(final String sequenceName) {

    ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
        @Override
        public Long execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getSequenceNextValString(sequenceName));
                resultSet = preparedStatement.executeQuery();
                resultSet.next();
                return resultSet.getLong(1);
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();

    Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
    return maxRecord;
}
 
Example 3
Source File: DefaultSequenceHandlerRepository.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void createSequence(final String sequenceName) {

    if (sequenceExists(sequenceName)) {
        return;
    }
    Work work = new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection
                        .prepareStatement(dialect.getCreateSequenceStrings(sequenceName, 1, 1)[0]);
                preparedStatement.execute();
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    sessionFactory.getCurrentSession().doWork(work);
}
 
Example 4
Source File: DefaultSequenceHandlerRepository.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public boolean sequenceExists(final String sequenceName) {
    ReturningWork<Boolean> work = new ReturningWork<Boolean>() {
        @Override
        public Boolean execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getQuerySequencesString());
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    if (sequenceName.equals(resultSet.getString(1))) {
                        return true;
                    }
                }
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }
            return false;

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    return sessionFactory.getCurrentSession().doReturningWork(work);
}
 
Example 5
Source File: DefaultSequenceHandlerRepository.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public void dropSequence(final String sequenceName) {

    Work work = new Work() {
        @Override
        public void execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getDropSequenceStrings(sequenceName)[0]);
                preparedStatement.execute();
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();
    sessionFactory.getCurrentSession().doWork(work);
}
 
Example 6
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Test
public void testMappedEntitiesStats() {

    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>> entitiesStatMap = getSecondLevelCacheEntitiesStats(statistics);
    logger.debug("All entities stats: {}", entitiesStatMap);

    String[] mappedEntities = {
            // ENTITY_STATS_PREFIX + "org.jboss.pnc.model.Artifact",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigSetRecord",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigurationSet",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration_AUD",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildEnvironment",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.BuildRecordPushResult",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.Product",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestone",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestoneRelease",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.ProductRelease",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.Project",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.RepositoryConfiguration",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.TargetRepository",
            ENTITY_STATS_PREFIX + "org.jboss.pnc.model.User",
            ENTITY_STATS_PREFIX + "build_configuration_parameters_AUD" };
    Set<String> mappedEntitiesSet = new HashSet<String>(Arrays.asList(mappedEntities));
    assertTrue(entitiesStatMap.keySet().containsAll(mappedEntitiesSet));
}
 
Example 7
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 8
Source File: IgniteTestHelper.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static <K> Map<K, BinaryObject> find(Session session, Class<?> class1, @SuppressWarnings("unchecked") K... ids) {
	SessionFactory sessionFactory = session.getSessionFactory();
	return find( sessionFactory, class1, ids );
}
 
Example 9
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Test
public void testMappedCollectionsStats() {

    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>> collectionStatMap = getSecondLevelCacheCollectionsStats(
            statistics);
    logger.debug("All collection stats: {}", collectionStatMap);

    String[] mappedCollections = {
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigurationSet.buildConfigurations",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigSetRecord.buildRecords",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion.buildConfigurations",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord.attributes",
            // COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.TargetRepository.artifacts",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration.genericParameters",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestone.performedBuilds",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration.dependants",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord.dependencies",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.RepositoryConfiguration.buildConfigurations",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration.dependencies",
            // COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.Artifact.distributedInProductMilestones",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion.attributes",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.User.buildRecords",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildEnvironment.attributes",
            // COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord.builtArtifacts",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigSetRecord.attributes",
            // COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductMilestone.distributedArtifacts",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.Project.buildConfigurations",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion.buildConfigurationSets",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildRecord.buildRecordPushResults",
            // COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.Artifact.dependantBuildRecords",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.Product.productVersions",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.ProductVersion.productMilestones",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfiguration.buildConfigurationSets",
            COLLECTION_STATS_PREFIX + "org.jboss.pnc.model.BuildConfigurationSet.buildConfigSetRecords" };
    Set<String> mappedCollectionsSet = new HashSet<String>(Arrays.asList(mappedCollections));
    assertTrue(collectionStatMap.keySet().containsAll(mappedCollectionsSet));
}
 
Example 10
Source File: CacheHandlerTest.java    From pnc with Apache License 2.0 4 votes vote down vote up
@Test
public void testFirstLevelCacheEviction() {

    // Session 3
    em_3 = getEmFactory().createEntityManager();
    Session session_3 = (Session) em_3.getDelegate();
    SessionFactory sessionFactory_3 = session_3.getSessionFactory();

    // Initialize sample build configurations, these cannot be done by DBUnit because of the Hibernate Envers
    // Auditing
    insertExampleBuildConfigurations(em_1, basicRepositoryConfiguration);

    BuildConfiguration buildConfig3 = BuildConfiguration.Builder.newBuilder()
            .id(3)
            .name("Test Build Configuration 3")
            .description("Test Build Configuration 3 Description")
            .project(Project.Builder.newBuilder().id(1).build())
            .repositoryConfiguration(basicRepositoryConfiguration)
            .buildScript("mvn install")
            .buildEnvironment(BuildEnvironment.Builder.newBuilder().id(1).build())
            .build();

    // Persist in Session 1
    em_1.getTransaction().begin();
    em_1.persist(buildConfig3);
    em_1.getTransaction().commit();

    Integer newBCId = buildConfig3.getId();

    // Entity is fetched very first time
    BuildConfiguration bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount1 = Double
            .parseDouble(genericStats.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount1 = Double
            .parseDouble(genericStats.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // fetch the BuildConfiguration entity again, no change in fetch count from 1st level cache nor access to 2nd
    // level
    // cache as there is no need for it
    bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats_2 = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount2 = Double
            .parseDouble(genericStats_2.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount2 = Double
            .parseDouble(genericStats_2.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // No change in fetch from 1st and 2nd level caches
    assertEquals((int) entityFetchCount1, (int) entityFetchCount2);
    assertEquals((int) secondLevelCacheHitCount2, (int) secondLevelCacheHitCount2);

    // Evict from first level cache
    session_3.evict(bc);

    // fetch one more time
    bc = (BuildConfiguration) session_3.load(BuildConfiguration.class, newBCId);

    SortedMap<String, HibernateMetric> genericStats_3 = getGenericStats(sessionFactory_3.getStatistics());
    double entityFetchCount3 = Double
            .parseDouble(genericStats_3.get("hibernate-orm.entities.fetch.count").getValue());
    double secondLevelCacheHitCount3 = Double
            .parseDouble(genericStats_3.get("hibernate-orm.second-level-cache.hit.count").getValue());

    // No change in fetch from 1st level cache as entity is not there anymore
    assertEquals((int) entityFetchCount2, (int) entityFetchCount3);
    // Change in fetch from 2nd level cache: the entity is not in 1st level cache anymore, so Hibernate gets it from
    // 2nd
    // level
    assertNotEquals(secondLevelCacheHitCount2, secondLevelCacheHitCount3);

    logger.debug(
            "Entity fetch count #1: {}, #2: {}, #3: {}",
            entityFetchCount1,
            entityFetchCount2,
            entityFetchCount3);
    logger.debug(
            "Second level cache hit count #1: {}, #2: {}, #3: {}",
            secondLevelCacheHitCount1,
            secondLevelCacheHitCount2,
            secondLevelCacheHitCount3);
}