下面列出了怎么用org.hibernate.engine.spi.SessionFactoryImplementor的API类实例代码及写法,或者点击链接到github查看源代码。
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
)
);
});
}
@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;
}
@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();
}
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();
}
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();
}
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
);
}
}
@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());
}
}
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());
}
}
@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;
}
@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;
}
/**
* 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);
}
}
public EntityBasedAssociationAttribute(
EntityPersister source,
SessionFactoryImplementor sessionFactory,
int attributeNumber,
String attributeName,
AssociationType attributeType,
BaselineAttributeInformation baselineInfo) {
super( source, sessionFactory, attributeNumber, attributeName, attributeType, baselineInfo );
}
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()
);
}
}
}
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);
}
}
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 );
}
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 );
}
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);
}
/**
* 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 );
}
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() );
}
}
@Override
public NativeQueryInterpreter initiateService(
SessionFactoryImplementor sessionFactory,
SessionFactoryOptions sessionFactoryOptions,
ServiceRegistryImplementor registry) {
return new NativeQueryInterpreterStandardImpl( sessionFactory );
}
@Override
protected UniqueEntityLoader buildBatchingLoader(
OuterJoinLoadable persister,
int batchSize,
LockMode lockMode,
SessionFactoryImplementor factory,
LoadQueryInfluencers influencers) {
return new PaddedBatchingEntityLoader( persister, batchSize, lockMode, factory, influencers );
}
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 );
}
/**
* 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 );
}
@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 + ")";
}
public ReactiveHQLQueryPlan(
String hql,
String collectionRole,
boolean shallow,
Map<String, Filter> enabledFilters,
SessionFactoryImplementor factory,
EntityGraphQueryHint entityGraphQueryHint) {
super( hql, collectionRole, shallow, enabledFilters, factory, entityGraphQueryHint );
}
/**
* 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 );
}
@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 );
}
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 );
}
@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 );
}
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() );
}