Java Code Examples for org.hibernate.engine.spi.SessionFactoryImplementor

The following examples show how to use org.hibernate.engine.spi.SessionFactoryImplementor. These examples are extracted from open source projects. 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
private void setCurrentLoggedUser(EntityManager entityManager) {
    Session session = entityManager.unwrap(Session.class);
    Dialect dialect = session.getSessionFactory().unwrap(SessionFactoryImplementor.class).getJdbcServices().getDialect();
    String loggedUser = ReflectionUtils.invokeMethod(
        dialect,
        "escapeLiteral",
        LoggedUser.get()
    );

    session.doWork(connection -> {
        update(
            connection,
            String.format(
                "SET @logged_user = '%s'", loggedUser
            )
        );
    });
}
 
Example 2
@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 3
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor sessionFactory) {
	final boolean hasArgs = !arguments.isEmpty();
	final StringBuilder buf = new StringBuilder( getName() );
	if ( hasArgs ) {
		buf.append( "(" );
		for ( int i = 0; i < arguments.size(); i++ ) {
			buf.append( arguments.get( i ) );
			if ( i < arguments.size() - 1 ) {
				buf.append( ", " );
			}
		}
		buf.append( ")" );
	}
	return buf.toString();
}
 
Example 4
protected String generateLockString(int lockTimeout) {
	final SessionFactoryImplementor factory = getLockable().getFactory();
	final LockOptions lockOptions = new LockOptions( getLockMode() );
	lockOptions.setTimeOut( lockTimeout );
	final SimpleSelect select = new SimpleSelect( factory.getDialect() )
			.setLockOptions( lockOptions )
			.setTableName( getLockable().getRootTableName() )
			.addColumn( getLockable().getRootTableIdentifierColumnNames()[0] )
			.addCondition( getLockable().getRootTableIdentifierColumnNames(), "=?" );
	if ( getLockable().isVersioned() ) {
		select.addCondition( getLockable().getVersionColumnName(), "=?" );
	}
	if ( factory.getSessionFactoryOptions().isCommentsEnabled() ) {
		select.setComment( getLockMode() + " lock " + getLockable().getEntityName() );
	}
	return select.toStatementString();
}
 
Example 5
Source Project: lams   Source File: CollectionType.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected String renderLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException {
	if ( !Hibernate.isInitialized( value ) ) {
		return "<uninitialized>";
	}

	final List<String> list = new ArrayList<>();
	Type elemType = getElementType( factory );
	Iterator itr = getElementsIterator( value );
	while ( itr.hasNext() ) {
		Object element = itr.next();
		if ( element == LazyPropertyInitializer.UNFETCHED_PROPERTY || !Hibernate.isInitialized( element ) ) {
			list.add( "<uninitialized>" );
		}
		else {
			list.add( elemType.toLoggableString( element, factory ) );
		}
	}
	return list.toString();
}
 
Example 6
public ReactiveDynamicBatchingCollectionInitializer(
		QueryableCollection collectionPersister,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	super( collectionPersister, factory, influencers );

	JoinWalker walker = buildJoinWalker( collectionPersister, factory, influencers );
	initFromWalker( walker );
	this.sqlTemplate = walker.getSQLString();
	this.alias = StringHelper.generateAlias( collectionPersister.getRole(), 0 );
	postInstantiate();

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf(
				"SQL-template for dynamic collection [%s] batch-fetching : %s",
				collectionPersister.getRole(),
				sqlTemplate
		);
	}
}
 
Example 7
@Override
public Object transformTuple(Object tuple[], String aliases[]) {
    try {
        if (!this.isInitialized) {
            this.initialize(aliases);
        } else {
            this.check(aliases);
        }

        Object result = this.resultClass.newInstance();

        for (int i = 0; i < aliases.length; ++i) {
            if (this.setters[i] != null) {
                this.setters[i].set(result, tuple[i], (SessionFactoryImplementor) null);
            }
        }

        return result;
    } catch (InstantiationException var5) {
        throw new HibernateException("Could not instantiate resultclass: " + this.resultClass.getName());
    } catch (IllegalAccessException var6) {
        throw new HibernateException("Could not instantiate resultclass: " + this.resultClass.getName());
    }
}
 
Example 8
public ReactiveOneToManyLoader(
		QueryableCollection oneToManyPersister,
		int batchSize,
		String subquery,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super(oneToManyPersister, factory, loadQueryInfluencers);

	initFromWalker( new OneToManyJoinWalker(
			oneToManyPersister,
			batchSize,
			subquery,
			factory,
			loadQueryInfluencers
	) );

	postInstantiate();
	if (LOG.isDebugEnabled()) {
		LOG.debugf("Static select for one-to-many %s: %s", oneToManyPersister.getRole(), getSQLString());
	}
}
 
Example 9
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException {
    if (arguments == null || arguments.size() < 2) {
        throw new IllegalArgumentException("The function must be passed 2 arguments");
    }

    String fragment;
    String ftsConfig;
    String field;
    String value;
    if (arguments.size() == 3) {
        ftsConfig = (String) arguments.get(0);
        field = (String) arguments.get(1);
        value = (String) arguments.get(2);
        fragment = field + " @@ plainto_tsquery(" + ftsConfig + ", " + value + ")";
    } else {
        field = (String) arguments.get(0);
        value = (String) arguments.get(1);
        fragment = field + " @@ plainto_tsquery(" + value + ")";
    }
    return fragment;
}
 
Example 10
@Override
public long getNumberOfAssociations(SessionFactory sessionFactory, AssociationStorageType type) {
	int asscociationCount = 0;
	Set<IgniteCache<Object, BinaryObject>> processedCaches = Collections.newSetFromMap( new IdentityHashMap<IgniteCache<Object, BinaryObject>, Boolean>() );

	for ( CollectionPersister collectionPersister : ( (SessionFactoryImplementor) sessionFactory ).getCollectionPersisters().values() ) {
		AssociationKeyMetadata associationKeyMetadata = ( (OgmCollectionPersister) collectionPersister ).getAssociationKeyMetadata();
		IgniteCache<Object, BinaryObject> associationCache = getAssociationCache( sessionFactory, associationKeyMetadata );
		if ( !processedCaches.contains( associationCache ) ) {
			asscociationCount += associationCache.size();
			processedCaches.add( associationCache );
		}
	}

	return asscociationCount;
}
 
Example 11
Source Project: spring-analysis-note   Source File: SpringSessionContext.java    License: MIT License 5 votes vote down vote up
/**
 * Create a new SpringSessionContext for the given Hibernate SessionFactory.
 * @param sessionFactory the SessionFactory to provide current Sessions for
 */
public SpringSessionContext(SessionFactoryImplementor sessionFactory) {
	this.sessionFactory = sessionFactory;
	try {
		JtaPlatform jtaPlatform = sessionFactory.getServiceRegistry().getService(JtaPlatform.class);
		this.transactionManager = jtaPlatform.retrieveTransactionManager();
		if (this.transactionManager != null) {
			this.jtaSessionContext = new SpringJtaSessionContext(sessionFactory);
		}
	}
	catch (Exception ex) {
		LogFactory.getLog(SpringSessionContext.class).warn(
				"Could not introspect Hibernate JtaPlatform for SpringJtaSessionContext", ex);
	}
}
 
Example 12
public EntityBasedAssociationAttribute(
		EntityPersister source,
		SessionFactoryImplementor sessionFactory,
		int attributeNumber,
		String attributeName,
		AssociationType attributeType,
		BaselineAttributeInformation baselineInfo) {
	super( source, sessionFactory, attributeNumber, attributeName, attributeType, baselineInfo );
}
 
Example 13
Source Project: lams   Source File: EntityLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
private EntityLoader(
		SessionFactoryImplementor factory,
		OuterJoinLoadable persister,
		String[] uniqueKeyColumnNames,
		Type uniqueKeyType,
		QueryBuildingParameters buildingParameters) throws MappingException {
	super( persister, factory, uniqueKeyColumnNames, uniqueKeyType, buildingParameters );
	if ( log.isDebugEnabled() ) {
		if ( buildingParameters.getLockOptions() != null ) {
			log.debugf(
					"Static select for entity %s [%s:%s]: %s",
					getEntityName(),
					buildingParameters.getLockOptions().getLockMode(),
					buildingParameters.getLockOptions().getTimeOut(),
					getStaticLoadQuery().getSqlStatement()
			);
		}
		else if ( buildingParameters.getLockMode() != null ) {
			log.debugf(
					"Static select for entity %s [%s]: %s",
					getEntityName(),
					buildingParameters.getLockMode(),
					getStaticLoadQuery().getSqlStatement()
			);
		}
	}
}
 
Example 14
public LegacyBatchingEntityLoader(
		OuterJoinLoadable persister,
		int maxBatchSize,
		LockOptions lockOptions,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) {
	super( persister );
	this.batchSizes = ArrayHelper.getBatchSizes( maxBatchSize );
	this.loaders = new Loader[ batchSizes.length ];
	for ( int i = 0; i < batchSizes.length; i++ ) {
		this.loaders[i] = new EntityLoader( persister, batchSizes[i], lockOptions, factory, loadQueryInfluencers);
	}
}
 
Example 15
Source Project: lams   Source File: EntityJoinFromElement.java    License: GNU General Public License v2.0 5 votes vote down vote up
public EntityJoinJoinSequenceImpl(
		SessionFactoryImplementor factory,
		EntityType entityType,
		String entityTableText,
		String entityTableAlias,
		JoinType joinType) {
	super( factory );
	this.factory = factory;
	this.entityType = entityType;
	this.entityTableText = entityTableText;
	this.entityTableAlias = entityTableAlias;
	this.joinType = joinType;

	setUseThetaStyle( false );
}
 
Example 16
Source Project: lams   Source File: CascadeEntityJoinWalker.java    License: GNU General Public License v2.0 5 votes vote down vote up
public CascadeEntityJoinWalker(
		OuterJoinLoadable persister,
		CascadingAction action,
		SessionFactoryImplementor factory)
		throws MappingException {
	super( persister, factory, LoadQueryInfluencers.NONE );
	this.cascadeAction = action;
	StringBuilder whereCondition = whereString( getAlias(), persister.getIdentifierColumnNames(), 1 )
			//include the discriminator and class-level where, but not filters
			.append( persister.filterFragment( getAlias(), Collections.EMPTY_MAP ) );

	initAll( whereCondition.toString(), "", LockOptions.READ );
}
 
Example 17
protected UniqueEntityLoader buildNonBatchingLoader(
			OuterJoinLoadable persister,
			LockOptions lockOptions,
			SessionFactoryImplementor factory,
			LoadQueryInfluencers influencers) {
		return new ReactivePlanEntityLoader.Builder( persister )
				.withLockMode( lockOptions.getLockMode() )
				.withInfluencers( influencers )
				.byPrimaryKey();
//		return new ReactiveEntityLoader( persister, factory, lockOptions.getLockMode(), influencers);
	}
 
Example 18
Source Project: lams   Source File: CacheKeyImplementation.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new key for a collection or entity instance.
 * Note that an entity name should always be the root entity
 * name, not a subclass entity name.
 *
 * @param id The identifier associated with the cached data
 * @param type The Hibernate type mapping
 * @param entityOrRoleName The entity or collection-role name.
 * @param tenantId The tenant identifier associated this data.
 * @param factory The session factory for which we are caching
 */
CacheKeyImplementation(
		final Object id,
		final Type type,
		final String entityOrRoleName,
		final String tenantId,
		final SessionFactoryImplementor factory) {
	this.id = id;
	this.type = type;
	this.entityOrRoleName = entityOrRoleName;
	this.tenantId = tenantId;
	this.hashCode = calculateHashCode( type, factory );
}
 
Example 19
Source Project: lams   Source File: CollectionElementLoader.java    License: GNU General Public License v2.0 5 votes vote down vote up
public CollectionElementLoader(
		QueryableCollection collectionPersister,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( factory, loadQueryInfluencers );

	this.keyType = collectionPersister.getKeyType();
	this.indexType = collectionPersister.getIndexType();
	this.persister = (OuterJoinLoadable) collectionPersister.getElementPersister();
	this.entityName = persister.getEntityName();

	JoinWalker walker = new EntityJoinWalker(
			persister,
			ArrayHelper.join(
					collectionPersister.getKeyColumnNames(),
					collectionPersister.toColumns( "index" )
			),
			1,
			LockMode.NONE,
			factory,
			loadQueryInfluencers
	);
	initFromWalker( walker );

	postInstantiate();

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Static select for entity %s: %s", entityName, getSQLString() );
	}

}
 
Example 20
@Override
public NativeQueryInterpreter initiateService(
		SessionFactoryImplementor sessionFactory,
		SessionFactoryOptions sessionFactoryOptions,
		ServiceRegistryImplementor registry) {
	return new NativeQueryInterpreterStandardImpl( sessionFactory );
}
 
Example 21
@Override
protected UniqueEntityLoader buildBatchingLoader(
		OuterJoinLoadable persister,
		int batchSize,
		LockMode lockMode,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	return new PaddedBatchingEntityLoader( persister, batchSize, lockMode, factory, influencers );
}
 
Example 22
Source Project: lams   Source File: OneToManyJoinWalker.java    License: GNU General Public License v2.0 5 votes vote down vote up
public OneToManyJoinWalker(
		QueryableCollection oneToManyPersister,
		int batchSize,
		String subquery,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( factory, loadQueryInfluencers );

	this.oneToManyPersister = oneToManyPersister;

	final OuterJoinLoadable elementPersister = (OuterJoinLoadable) oneToManyPersister.getElementPersister();
	final String alias = generateRootAlias( oneToManyPersister.getRole() );

	walkEntityTree( elementPersister, alias );

	List allAssociations = new ArrayList();
	allAssociations.addAll( associations );
	allAssociations.add(
			OuterJoinableAssociation.createRoot(
					oneToManyPersister.getCollectionType(),
					alias,
					getFactory()
			)
	);
	initPersisters( allAssociations, LockMode.NONE );
	initStatementString( elementPersister, alias, batchSize, subquery );
}
 
Example 23
Source Project: lams   Source File: QueryPlanCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs the QueryPlanCache to be used by the given SessionFactory
 *
 * @param factory The SessionFactory
 */
@SuppressWarnings("deprecation")
public QueryPlanCache(final SessionFactoryImplementor factory) {
	this.factory = factory;

	Integer maxParameterMetadataCount = ConfigurationHelper.getInteger(
			Environment.QUERY_PLAN_CACHE_PARAMETER_METADATA_MAX_SIZE,
			factory.getProperties()
	);
	if ( maxParameterMetadataCount == null ) {
		maxParameterMetadataCount = ConfigurationHelper.getInt(
				Environment.QUERY_PLAN_CACHE_MAX_STRONG_REFERENCES,
				factory.getProperties(),
				DEFAULT_PARAMETER_METADATA_MAX_COUNT
		);
	}
	Integer maxQueryPlanCount = ConfigurationHelper.getInteger(
			Environment.QUERY_PLAN_CACHE_MAX_SIZE,
			factory.getProperties()
	);
	if ( maxQueryPlanCount == null ) {
		maxQueryPlanCount = ConfigurationHelper.getInt(
				Environment.QUERY_PLAN_CACHE_MAX_SOFT_REFERENCES,
				factory.getProperties(),
				DEFAULT_QUERY_PLAN_MAX_COUNT
		);
	}

	queryPlanCache = new BoundedConcurrentHashMap( maxQueryPlanCount, 20, BoundedConcurrentHashMap.Eviction.LIRS );
	parameterMetadataCache = new BoundedConcurrentHashMap<>(
			maxParameterMetadataCount,
			20,
			BoundedConcurrentHashMap.Eviction.LIRS
	);

	nativeQueryInterpreter = factory.getServiceRegistry().getService( NativeQueryInterpreter.class );
}
 
Example 24
Source Project: blog-tutorials   Source File: PostgreSQLFTSFunction.java    License: MIT License 5 votes vote down vote up
@Override
public String render(Type type, List args, SessionFactoryImplementor factory) throws QueryException {

	if (args == null || args.size() != 3) {
		throw new IllegalArgumentException("The function must be passed 2 arguments");
	}

	String language = (String) args.get(0);
	String field = (String) args.get(1);
	String searchString = (String) args.get(2);
	return field + " @@ to_tsquery('" + language + "', " + searchString + ")";
}
 
Example 25
public ReactiveHQLQueryPlan(
		String hql,
		String collectionRole,
		boolean shallow,
		Map<String, Filter> enabledFilters,
		SessionFactoryImplementor factory,
		EntityGraphQueryHint entityGraphQueryHint) {
	super( hql, collectionRole, shallow, enabledFilters, factory, entityGraphQueryHint );
}
 
Example 26
/**
 * Builds a batch-fetch capable CollectionInitializer for basic and many-to-many collections (collections with
 * a dedicated collection table).
 *
 * @param persister THe collection persister
 * @param maxBatchSize The maximum number of keys to batch-fetch together
 * @param factory The SessionFactory
 * @param influencers Any influencers that should affect the built query
 *
 * @return The batch-fetch capable collection initializer
 */
public CollectionInitializer createBatchingCollectionInitializer(
		QueryableCollection persister,
		int maxBatchSize,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	if ( maxBatchSize <= 1 ) {
		// no batching
		return buildNonBatchingLoader( persister, factory, influencers );
	}

	return createRealBatchingCollectionInitializer( persister, maxBatchSize, factory, influencers );
}
 
Example 27
@Override
public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) {
	if ( arguments.size() > 1 ) {
		if ( "distinct".equalsIgnoreCase( arguments.get( 0 ).toString() ) ) {
			return renderCountDistinct( arguments, factory.getDialect() );
		}
	}
	return super.render( firstArgumentType, arguments, factory );
}
 
Example 28
Source Project: lams   Source File: AbstractEntityTuplizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Serializable determineEntityId(
		Object entity,
		AssociationType associationType,
		SharedSessionContractImplementor session,
		SessionFactoryImplementor sessionFactory) {
	if ( entity == null ) {
		return null;
	}

	if ( HibernateProxy.class.isInstance( entity ) ) {
		// entity is a proxy, so we know it is not transient; just return ID from proxy
		return ( (HibernateProxy) entity ).getHibernateLazyInitializer().getIdentifier();
	}

	if ( session != null ) {
		final EntityEntry pcEntry = session.getPersistenceContext().getEntry( entity );
		if ( pcEntry != null ) {
			// entity managed; return ID.
			return pcEntry.getId();
		}
	}

	final EntityPersister persister = resolveEntityPersister(
			entity,
			associationType,
			session,
			sessionFactory
	);

	return persister.getIdentifier( entity, session );
}
 
Example 29
@Override
protected CollectionInitializer createRealBatchingOneToManyInitializer(
		QueryableCollection persister,
		int maxBatchSize,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	final int[] batchSizes = ArrayHelper.getBatchSizes( maxBatchSize );
	final Loader[] loaders = new Loader[ batchSizes.length ];
	for ( int i = 0; i < batchSizes.length; i++ ) {
		loaders[i] = new OneToManyLoader( persister, batchSizes[i], factory, loadQueryInfluencers );
	}
	return new LegacyBatchingCollectionInitializer( persister, batchSizes, loaders );
}
 
Example 30
private CompletionStage<Void> checkIdClass(
		final EntityPersister persister,
		final LoadEvent event,
		final LoadEventListener.LoadType loadType,
		final Class<?> idClass) {
	// we may have the kooky jpa requirement of allowing find-by-id where
	// "id" is the "simple pk value" of a dependent objects parent.  This
	// is part of its generally goofy "derived identity" "feature"
	final IdentifierProperty identifierProperty = persister.getEntityMetamodel().getIdentifierProperty();
	if ( identifierProperty.isEmbedded() ) {
		final EmbeddedComponentType dependentIdType = (EmbeddedComponentType) identifierProperty.getType();
		if ( dependentIdType.getSubtypes().length == 1 ) {
			final Type singleSubType = dependentIdType.getSubtypes()[0];
			if ( singleSubType.isEntityType() ) {
				final EntityType dependentParentType = (EntityType) singleSubType;
				final SessionFactoryImplementor factory = event.getSession().getFactory();
				final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( factory );
				if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
					// yep that's what we have...
					return loadByDerivedIdentitySimplePkValue( event, loadType, persister,
							dependentIdType, factory.getMetamodel().entityPersister( dependentParentType.getAssociatedEntityName() )
					);
				}
			}
		}
	}
	throw new TypeMismatchException(
			"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass + ", got " + event.getEntityId().getClass() );
}