6 - SQM based on JPA type system

- focus on reducing compilation errors
This commit is contained in:
Steve Ebersole 2019-07-09 15:06:56 -05:00 committed by Andrea Boriero
parent d0116d7caa
commit c6a11d99fd
290 changed files with 3067 additions and 10258 deletions

View File

@ -8,7 +8,7 @@
//$Id$ //$Id$
package org.hibernate.userguide.proxy.tuplizer; package org.hibernate.userguide.proxy.tuplizer;
import org.hibernate.mapping.Component; import org.hibernate.mapping.Component;
import org.hibernate.metamodel.spi.Instantiator; import org.hibernate.tuple.Instantiator;
import org.hibernate.tuple.component.PojoComponentTuplizer; import org.hibernate.tuple.component.PojoComponentTuplizer;
/** /**

View File

@ -10,7 +10,7 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.Getter;
import org.hibernate.property.access.spi.Setter; import org.hibernate.property.access.spi.Setter;
import org.hibernate.proxy.ProxyFactory; import org.hibernate.proxy.ProxyFactory;
import org.hibernate.metamodel.spi.Instantiator; import org.hibernate.tuple.Instantiator;
import org.hibernate.tuple.entity.EntityMetamodel; import org.hibernate.tuple.entity.EntityMetamodel;
import org.hibernate.tuple.entity.PojoEntityTuplizer; import org.hibernate.tuple.entity.PojoEntityTuplizer;

View File

@ -11,7 +11,7 @@ package org.hibernate.userguide.proxy.tuplizer;
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.metamodel.spi.Instantiator; import org.hibernate.tuple.Instantiator;
/** /**
* @author Emmanuel Bernard * @author Emmanuel Bernard

View File

@ -13,7 +13,6 @@ import java.time.ZoneOffset;
import java.util.List; import java.util.List;
import javax.persistence.PersistenceException; import javax.persistence.PersistenceException;
import org.hibernate.Criteria;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.dialect.H2Dialect; import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.dialect.Oracle8iDialect;
@ -38,8 +37,6 @@ import org.hibernate.testing.RequiresDialect;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.jboss.logging.Logger;
import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping; import static org.hibernate.testing.junit4.ExtraAssertions.assertTyping;
import static org.hibernate.testing.transaction.TransactionUtil.doInJPA; import static org.hibernate.testing.transaction.TransactionUtil.doInJPA;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;

View File

@ -8,7 +8,6 @@ package org.hibernate.test.c3p0;
import java.util.List; import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session; import org.hibernate.Session;
import org.junit.Assert; import org.junit.Assert;

View File

@ -7,6 +7,8 @@
package org.hibernate; package org.hibernate;
import java.util.Locale; import java.util.Locale;
import javax.persistence.CacheRetrieveMode;
import javax.persistence.CacheStoreMode;
/** /**
* Controls how the session interacts with the second-level cache and query cache. * Controls how the session interacts with the second-level cache and query cache.
@ -19,37 +21,44 @@ public enum CacheMode {
/** /**
* The session may read items from the cache, and add items to the cache. * The session may read items from the cache, and add items to the cache.
*/ */
NORMAL( true, true ), NORMAL( CacheStoreMode.USE, CacheRetrieveMode.USE ),
/** /**
* The session will never interact with the cache, except to invalidate * The session will never interact with the cache, except to invalidate
* cache items when updates occur. * cache items when updates occur.
*/ */
IGNORE( false, false ), IGNORE( CacheStoreMode.BYPASS, CacheRetrieveMode.BYPASS ),
/** /**
* The session may read items from the cache, but will not add items, * The session may read items from the cache, but will not add items,
* except to invalidate items when updates occur. * except to invalidate items when updates occur.
*/ */
GET( false, true ), GET( CacheStoreMode.BYPASS, CacheRetrieveMode.USE ),
/** /**
* The session will never read items from the cache, but will add items * The session will never read items from the cache, but will add items
* to the cache as it reads them from the database. * to the cache as it reads them from the database.
*/ */
PUT( true, false ), PUT( CacheStoreMode.USE, CacheRetrieveMode.BYPASS ),
/** /**
* The session will never read items from the cache, but will add items * The session will never read items from the cache, but will add items
* to the cache as it reads them from the database. In this mode, the * to the cache as it reads them from the database. In this mode, the
* effect of <tt>hibernate.cache.use_minimal_puts</tt> is bypassed, in * effect of <tt>hibernate.cache.use_minimal_puts</tt> is bypassed, in
* order to <em>force</em> a cache refresh. * order to <em>force</em> a cache refresh.
*/ */
REFRESH( true, false ); REFRESH( CacheStoreMode.REFRESH, CacheRetrieveMode.BYPASS );
private final CacheStoreMode storeMode;
private final CacheRetrieveMode retrieveMode;
private final boolean isPutEnabled; CacheMode(CacheStoreMode storeMode, CacheRetrieveMode retrieveMode) {
private final boolean isGetEnabled; this.storeMode = storeMode;
this.retrieveMode = retrieveMode;
}
private CacheMode( boolean isPutEnabled, boolean isGetEnabled) { public CacheStoreMode getJpaStoreMode() {
this.isPutEnabled = isPutEnabled; return storeMode;
this.isGetEnabled = isGetEnabled; }
public CacheRetrieveMode getJpaRetrieveMode() {
return retrieveMode;
} }
/** /**
@ -58,7 +67,7 @@ public enum CacheMode {
* @return {@code true} if cache reads are allowed; {@code false} otherwise. * @return {@code true} if cache reads are allowed; {@code false} otherwise.
*/ */
public boolean isGetEnabled() { public boolean isGetEnabled() {
return isGetEnabled; return retrieveMode == CacheRetrieveMode.USE;
} }
/** /**
@ -67,7 +76,7 @@ public enum CacheMode {
* @return {@code true} if cache writes are allowed; {@code false} otherwise. * @return {@code true} if cache writes are allowed; {@code false} otherwise.
*/ */
public boolean isPutEnabled() { public boolean isPutEnabled() {
return isPutEnabled; return storeMode == CacheStoreMode.USE || storeMode == CacheStoreMode.REFRESH;
} }
/** /**
@ -91,4 +100,34 @@ public enum CacheMode {
throw new MappingException( "Unknown Cache Mode: " + setting ); throw new MappingException( "Unknown Cache Mode: " + setting );
} }
} }
public static CacheMode fromJpaModes(CacheRetrieveMode retrieveMode, CacheStoreMode storeMode) {
if ( storeMode == null ) {
storeMode = CacheStoreMode.BYPASS;
}
if ( retrieveMode == null ) {
retrieveMode = CacheRetrieveMode.BYPASS;
}
switch ( storeMode ) {
case BYPASS: {
return retrieveMode == CacheRetrieveMode.USE
? GET
: IGNORE;
}
case REFRESH: {
// technically should combo `CacheStoreMode#REFRESH` and `CacheRetrieveMode#USE` be illegal?
return REFRESH;
}
case USE: {
return retrieveMode == CacheRetrieveMode.USE
? NORMAL
: PUT;
}
default: {
throw new UnsupportedOperationException( "Unrecognized CacheStoreMode : " + storeMode );
}
}
}
} }

View File

@ -1,566 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate;
import java.util.List;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.sql.JoinType;
import org.hibernate.transform.ResultTransformer;
/**
* <tt>Criteria</tt> is a simplified API for retrieving entities
* by composing <tt>Criterion</tt> objects. This is a very
* convenient approach for functionality like "search" screens
* where there is a variable number of conditions to be placed
* upon the result set.<br>
* <br>
* The <tt>Session</tt> is a factory for <tt>Criteria</tt>.
* <tt>Criterion</tt> instances are usually obtained via
* the factory methods on <tt>Restrictions</tt>. eg.
* <pre>
* List cats = session.createCriteria(Cat.class)
* .add( Restrictions.like("name", "Iz%") )
* .add( Restrictions.gt( "weight", new Float(minWeight) ) )
* .addOrder( Order.asc("age") )
* .list();
* </pre>
* You may navigate associations using <tt>createAlias()</tt> or
* <tt>createCriteria()</tt>.
* <pre>
* List cats = session.createCriteria(Cat.class)
* .createCriteria("kittens")
* .add( Restrictions.like("name", "Iz%") )
* .list();
* </pre>
* <pre>
* List cats = session.createCriteria(Cat.class)
* .createAlias("kittens", "kit")
* .add( Restrictions.like("kit.name", "Iz%") )
* .list();
* </pre>
* You may specify projection and aggregation using <tt>Projection</tt>
* instances obtained via the factory methods on <tt>Projections</tt>.
* <pre>
* List cats = session.createCriteria(Cat.class)
* .setProjection( Projections.projectionList()
* .add( Projections.rowCount() )
* .add( Projections.avg("weight") )
* .add( Projections.max("weight") )
* .add( Projections.min("weight") )
* .add( Projections.groupProperty("color") )
* )
* .addOrder( Order.asc("color") )
* .list();
* </pre>
*
* @see Session#createCriteria(java.lang.Class)
* @see org.hibernate.criterion.Restrictions
* @see org.hibernate.criterion.Projections
* @see org.hibernate.criterion.Order
* @see org.hibernate.criterion.Criterion
* @see org.hibernate.criterion.Projection
* @see org.hibernate.criterion.DetachedCriteria a disconnected version of this API
* @author Gavin King
*/
public interface Criteria extends CriteriaSpecification {
/**
* Get the alias of the entity encapsulated by this criteria instance.
*
* @return The alias for the encapsulated entity.
*/
public String getAlias();
/**
* Used to specify that the query results will be a projection (scalar in
* nature). Implicitly specifies the {@link #PROJECTION} result transformer.
* <p/>
* The individual components contained within the given
* {@link Projection projection} determines the overall "shape" of the
* query result.
*
* @param projection The projection representing the overall "shape" of the
* query results.
* @return this (for method chaining)
*/
public Criteria setProjection(Projection projection);
/**
* Add a {@link Criterion restriction} to constrain the results to be
* retrieved.
*
* @param criterion The {@link Criterion criterion} object representing the
* restriction to be applied.
* @return this (for method chaining)
*/
public Criteria add(Criterion criterion);
/**
* Add an {@link Order ordering} to the result set.
*
* @param order The {@link Order order} object representing an ordering
* to be applied to the results.
* @return this (for method chaining)
*/
public Criteria addOrder(Order order);
/**
* Specify an association fetching strategy for an association or a
* collection of values.
*
* @param associationPath a dot separated property path
* @param mode The fetch mode for the referenced association
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem applying the given fetch mode
*/
public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException;
/**
* Set the lock mode of the current entity.
*
* @param lockMode The lock mode to be applied
*
* @return this (for method chaining)
*/
public Criteria setLockMode(LockMode lockMode);
/**
* Set the lock mode of the aliased entity.
*
* @param alias The previously assigned alias representing the entity to
* which the given lock mode should apply.
* @param lockMode The lock mode to be applied
*
* @return this (for method chaining)
*/
public Criteria setLockMode(String alias, LockMode lockMode);
/**
* Join an association, assigning an alias to the joined association.
* <p/>
* Functionally equivalent to {@link #createAlias(String, String, JoinType )} using
* {@link JoinType#INNER_JOIN} for the joinType.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createAlias(String associationPath, String alias) throws HibernateException;
/**
* Join an association using the specified join-type, assigning an alias
* to the joined association.
* <p/>
* The joinType is expected to be one of {@link JoinType#INNER_JOIN} (the default),
* {@link JoinType#FULL_JOIN}, or {@link JoinType#LEFT_OUTER_JOIN}.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException;
/**
* Join an association using the specified join-type, assigning an alias
* to the joined association.
* <p/>
* The joinType is expected to be one of {@link #INNER_JOIN} (the default),
* {@link #FULL_JOIN}, or {@link #LEFT_JOIN}.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem creating the sub criteria
* @deprecated use {@link #createAlias(String, String, org.hibernate.sql.JoinType)}
*/
@Deprecated
public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException;
/**
* Join an association using the specified join-type, assigning an alias
* to the joined association.
* <p/>
* The joinType is expected to be one of {@link JoinType#INNER_JOIN} (the default),
* {@link JoinType#FULL_JOIN}, or {@link JoinType#LEFT_OUTER_JOIN}.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
* @param withClause The criteria to be added to the join condition (<tt>ON</tt> clause)
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException;
/**
* Join an association using the specified join-type, assigning an alias
* to the joined association.
* <p/>
* The joinType is expected to be one of {@link #INNER_JOIN} (the default),
* {@link #FULL_JOIN}, or {@link #LEFT_JOIN}.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
* @param withClause The criteria to be added to the join condition (<tt>ON</tt> clause)
*
* @return this (for method chaining)
*
* @throws HibernateException Indicates a problem creating the sub criteria
* @deprecated use {@link #createAlias(String, String, JoinType, Criterion)}
*/
@Deprecated
public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity.
* <p/>
* Functionally equivalent to {@link #createCriteria(String, org.hibernate.sql.JoinType)} using
* {@link JoinType#INNER_JOIN} for the joinType.
*
* @param associationPath A dot-separated property path
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createCriteria(String associationPath) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity, using the
* specified join type.
*
* @param associationPath A dot-separated property path
* @param joinType The type of join to use.
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createCriteria(String associationPath, JoinType joinType) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity, using the
* specified join type.
*
* @param associationPath A dot-separated property path
* @param joinType The type of join to use.
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
* @deprecated use {@link #createAlias(String, String, org.hibernate.sql.JoinType)}
*/
@Deprecated
public Criteria createCriteria(String associationPath, int joinType) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity,
* assigning the given alias.
* <p/>
* Functionally equivalent to {@link #createCriteria(String, String, org.hibernate.sql.JoinType)} using
* {@link JoinType#INNER_JOIN} for the joinType.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createCriteria(String associationPath, String alias) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity,
* assigning the given alias and using the specified join type.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity,
* assigning the given alias and using the specified join type.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
* @deprecated use {@link #createCriteria(String, org.hibernate.sql.JoinType)}
*/
@Deprecated
public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity,
* assigning the given alias and using the specified join type.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
* @param withClause The criteria to be added to the join condition (<tt>ON</tt> clause)
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
*/
public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException;
/**
* Create a new <tt>Criteria</tt>, "rooted" at the associated entity,
* assigning the given alias and using the specified join type.
*
* @param associationPath A dot-separated property path
* @param alias The alias to assign to the joined association (for later reference).
* @param joinType The type of join to use.
* @param withClause The criteria to be added to the join condition (<tt>ON</tt> clause)
*
* @return the created "sub criteria"
*
* @throws HibernateException Indicates a problem creating the sub criteria
* @deprecated use {@link #createCriteria(String, String, org.hibernate.sql.JoinType, org.hibernate.criterion.Criterion)}
*/
@Deprecated
public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException;
/**
* Set a strategy for handling the query results. This determines the
* "shape" of the query result.
*
* @param resultTransformer The transformer to apply
* @return this (for method chaining)
*
* @see #ROOT_ENTITY
* @see #DISTINCT_ROOT_ENTITY
* @see #ALIAS_TO_ENTITY_MAP
* @see #PROJECTION
*/
public Criteria setResultTransformer(ResultTransformer resultTransformer);
/**
* Set a limit upon the number of objects to be retrieved.
*
* @param maxResults the maximum number of results
* @return this (for method chaining)
*/
public Criteria setMaxResults(int maxResults);
/**
* Set the first result to be retrieved.
*
* @param firstResult the first result to retrieve, numbered from <tt>0</tt>
* @return this (for method chaining)
*/
public Criteria setFirstResult(int firstResult);
/**
* Was the read-only/modifiable mode explicitly initialized?
*
* @return true, the read-only/modifiable mode was explicitly initialized; false, otherwise.
*
* @see Criteria#setReadOnly(boolean)
*/
public boolean isReadOnlyInitialized();
/**
* Should entities and proxies loaded by this Criteria be put in read-only mode? If the
* read-only/modifiable setting was not initialized, then the default
* read-only/modifiable setting for the persistence context is returned instead.
* @see Criteria#setReadOnly(boolean)
* @see org.hibernate.engine.spi.PersistenceContext#isDefaultReadOnly()
*
* The read-only/modifiable setting has no impact on entities/proxies returned by the
* Criteria that existed in the session before the Criteria was executed.
*
* @return true, entities and proxies loaded by the criteria will be put in read-only mode
* false, entities and proxies loaded by the criteria will be put in modifiable mode
* @throws IllegalStateException if <code>isReadOnlyInitialized()</code> returns <code>false</code>
* and this Criteria is not associated with a session.
* @see Criteria#isReadOnlyInitialized()
*/
public boolean isReadOnly();
/**
* Set the read-only/modifiable mode for entities and proxies
* loaded by this Criteria. This setting overrides the default setting
* for the persistence context.
* @see org.hibernate.engine.spi.PersistenceContext#isDefaultReadOnly()
*
* To set the default read-only/modifiable setting used for
* entities and proxies that are loaded into the session:
* @see org.hibernate.engine.spi.PersistenceContext#setDefaultReadOnly(boolean)
* @see org.hibernate.Session#setDefaultReadOnly(boolean)
*
* Read-only entities are not dirty-checked and snapshots of persistent
* state are not maintained. Read-only entities can be modified, but
* changes are not persisted.
*
* When a proxy is initialized, the loaded entity will have the same
* read-only/modifiable setting as the uninitialized
* proxy has, regardless of the session's current setting.
*
* The read-only/modifiable setting has no impact on entities/proxies
* returned by the criteria that existed in the session before the criteria was executed.
*
* @param readOnly true, entities and proxies loaded by the criteria will be put in read-only mode
* false, entities and proxies loaded by the criteria will be put in modifiable mode
* @return {@code this}, for method chaining
*/
public Criteria setReadOnly(boolean readOnly);
/**
* Set a fetch size for the underlying JDBC query.
*
* @param fetchSize the fetch size
* @return this (for method chaining)
*
* @see java.sql.Statement#setFetchSize
*/
public Criteria setFetchSize(int fetchSize);
/**
* Set a timeout for the underlying JDBC query.
*
* @param timeout The timeout value to apply.
* @return this (for method chaining)
*
* @see java.sql.Statement#setQueryTimeout
*/
public Criteria setTimeout(int timeout);
/**
* Enable caching of this query result, provided query caching is enabled
* for the underlying session factory.
*
* @param cacheable Should the result be considered cacheable; default is
* to not cache (false).
* @return this (for method chaining)
*/
public Criteria setCacheable(boolean cacheable);
/**
* Set the name of the cache region to use for query result caching.
*
* @param cacheRegion the name of a query cache region, or <tt>null</tt>
* for the default query cache
* @return this (for method chaining)
*
* @see #setCacheable
*/
public Criteria setCacheRegion(String cacheRegion);
/**
* Add a comment to the generated SQL.
*
* @param comment a human-readable string
* @return this (for method chaining)
*/
public Criteria setComment(String comment);
/**
* Add a DB query hint to the SQL. These differ from JPA's {@link javax.persistence.QueryHint}, which is specific
* to the JPA implementation and ignores DB vendor-specific hints. Instead, these are intended solely for the
* vendor-specific hints, such as Oracle's optimizers. Multiple query hints are supported; the Dialect will
* determine concatenation and placement.
*
* @param hint The database specific query hint to add.
* @return this (for method chaining)
*/
public Criteria addQueryHint(String hint);
/**
* Override the flush mode for this particular query.
*
* @param flushMode The flush mode to use.
* @return this (for method chaining)
*/
public Criteria setFlushMode(FlushMode flushMode);
/**
* Override the cache mode for this particular query.
*
* @param cacheMode The cache mode to use.
* @return this (for method chaining)
*/
public Criteria setCacheMode(CacheMode cacheMode);
/**
* Get the results.
*
* @return The list of matched query results.
*
* @throws HibernateException Indicates a problem either translating the criteria to SQL,
* exeucting the SQL or processing the SQL results.
*/
public List list() throws HibernateException;
/**
* Get the results as an instance of {@link ScrollableResults}.
*
* @return The {@link ScrollableResults} representing the matched
* query results.
*
* @throws HibernateException Indicates a problem either translating the criteria to SQL,
* exeucting the SQL or processing the SQL results.
*/
public ScrollableResults scroll() throws HibernateException;
/**
* Get the results as an instance of {@link ScrollableResults} based on the
* given scroll mode.
*
* @param scrollMode Indicates the type of underlying database cursor to
* request.
*
* @return The {@link ScrollableResults} representing the matched
* query results.
*
* @throws HibernateException Indicates a problem either translating the criteria to SQL,
* exeucting the SQL or processing the SQL results.
*/
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException;
/**
* Convenience method to return a single instance that matches
* the query, or null if the query returns no results.
*
* @return the single result or <tt>null</tt>
* @throws HibernateException if there is more than one matching result
*/
public Object uniqueResult() throws HibernateException;
}

View File

@ -10,6 +10,7 @@ import java.io.Closeable;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import org.hibernate.annotations.Remove;
import org.hibernate.query.NativeQuery; import org.hibernate.query.NativeQuery;
/** /**
@ -173,6 +174,8 @@ public interface StatelessSession extends SharedSessionContract, AutoCloseable,
@Deprecated @Deprecated
Connection connection(); Connection connection();
@Override @Remove
NativeQuery createSQLQuery(String queryString); default <@Remove T> NativeQuery<T> createSQLQuery(String queryString) {
return createNativeQuery( queryString );
}
} }

View File

@ -0,0 +1,33 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.TYPE_PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Indicates that the annotated element is planned for removal as part
* of a deprecation lifecycle.
*
* @apiNote Intended for use at development-time for developers to better understand
* the lifecycle of the annotated element.
*
* @author Steve Ebersole
*/
@Target({METHOD, FIELD, TYPE, PACKAGE, CONSTRUCTOR, TYPE_PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface Remove {
}

View File

@ -27,7 +27,6 @@ import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.cache.spi.TimestampsCacheFactory;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.internal.SessionFactoryImpl; import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.loader.BatchFetchStyle; import org.hibernate.loader.BatchFetchStyle;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;

View File

@ -45,7 +45,6 @@ import org.hibernate.engine.config.internal.ConfigurationServiceImpl;
import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData; import org.hibernate.engine.jdbc.env.spi.ExtractedDatabaseMetaData;
import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.id.uuid.LocalObjectUuidHelper; import org.hibernate.id.uuid.LocalObjectUuidHelper;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.log.DeprecationLogger; import org.hibernate.internal.log.DeprecationLogger;
@ -187,7 +186,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions {
private EntityTuplizerFactory entityTuplizerFactory = new EntityTuplizerFactory(); private EntityTuplizerFactory entityTuplizerFactory = new EntityTuplizerFactory();
private boolean checkNullability; private boolean checkNullability;
private boolean initializeLazyStateOutsideTransactions; private boolean initializeLazyStateOutsideTransactions;
private MultiTableBulkIdStrategy multiTableBulkIdStrategy;
private TempTableDdlTransactionHandling tempTableDdlTransactionHandling; private TempTableDdlTransactionHandling tempTableDdlTransactionHandling;
private BatchFetchStyle batchFetchStyle; private BatchFetchStyle batchFetchStyle;
private boolean delayBatchFetchLoaderCreations; private boolean delayBatchFetchLoaderCreations;
@ -334,12 +332,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions {
configurationSettings.get( MULTI_TENANT_IDENTIFIER_RESOLVER ) configurationSettings.get( MULTI_TENANT_IDENTIFIER_RESOLVER )
); );
this.multiTableBulkIdStrategy = strategySelector.resolveDefaultableStrategy(
MultiTableBulkIdStrategy.class,
configurationSettings.get( HQL_BULK_ID_STRATEGY ),
jdbcServices.getJdbcEnvironment().getDialect().getDefaultMultiTableBulkIdStrategy()
);
this.batchFetchStyle = BatchFetchStyle.interpret( configurationSettings.get( BATCH_FETCH_STYLE ) ); this.batchFetchStyle = BatchFetchStyle.interpret( configurationSettings.get( BATCH_FETCH_STYLE ) );
this.delayBatchFetchLoaderCreations = cfgService.getSetting( DELAY_ENTITY_LOADER_CREATIONS, BOOLEAN, true ); this.delayBatchFetchLoaderCreations = cfgService.getSetting( DELAY_ENTITY_LOADER_CREATIONS, BOOLEAN, true );
this.defaultBatchFetchSize = ConfigurationHelper.getInt( DEFAULT_BATCH_FETCH_SIZE, configurationSettings, -1 ); this.defaultBatchFetchSize = ConfigurationHelper.getInt( DEFAULT_BATCH_FETCH_SIZE, configurationSettings, -1 );
@ -797,11 +789,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions {
return initializeLazyStateOutsideTransactions; return initializeLazyStateOutsideTransactions;
} }
@Override
public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() {
return multiTableBulkIdStrategy;
}
@Override @Override
public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() { public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() {
return tempTableDdlTransactionHandling; return tempTableDdlTransactionHandling;
@ -1168,10 +1155,6 @@ public class SessionFactoryOptionsBuilder implements SessionFactoryOptions {
this.entityTuplizerFactory.registerDefaultTuplizerClass( entityMode, tuplizerClass ); this.entityTuplizerFactory.registerDefaultTuplizerClass( entityMode, tuplizerClass );
} }
public void applyMultiTableBulkIdStrategy(MultiTableBulkIdStrategy strategy) {
this.multiTableBulkIdStrategy = strategy;
}
public void applyTempTableDdlTransactionHandling(TempTableDdlTransactionHandling handling) { public void applyTempTableDdlTransactionHandling(TempTableDdlTransactionHandling handling) {
this.tempTableDdlTransactionHandling = handling; this.tempTableDdlTransactionHandling = handling;
} }

View File

@ -89,14 +89,6 @@ import org.hibernate.engine.transaction.jta.platform.internal.WebSphereJtaPlatfo
import org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform; import org.hibernate.engine.transaction.jta.platform.internal.WebSphereLibertyJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.internal.WeblogicJtaPlatform; import org.hibernate.engine.transaction.jta.platform.internal.WeblogicJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.event.internal.EntityCopyAllowedLoggedObserver;
import org.hibernate.event.internal.EntityCopyAllowedObserver;
import org.hibernate.event.internal.EntityCopyNotAllowedObserver;
import org.hibernate.event.spi.EntityCopyObserver;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.persistent.PersistentTableBulkIdStrategy;
import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl; import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder; import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;

View File

@ -23,7 +23,6 @@ import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.cache.spi.TimestampsCacheFactory;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.loader.BatchFetchStyle; import org.hibernate.loader.BatchFetchStyle;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;
import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode; import org.hibernate.resource.jdbc.spi.PhysicalConnectionHandlingMode;

View File

@ -25,7 +25,6 @@ import org.hibernate.cache.spi.TimestampsCacheFactory;
import org.hibernate.cfg.BaselineSessionEventsListenerBuilder; import org.hibernate.cfg.BaselineSessionEventsListenerBuilder;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.jpa.spi.JpaCompliance; import org.hibernate.jpa.spi.JpaCompliance;
import org.hibernate.loader.BatchFetchStyle; import org.hibernate.loader.BatchFetchStyle;
import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.proxy.EntityNotFoundDelegate;
@ -157,11 +156,6 @@ public class AbstractDelegatingSessionFactoryOptions implements SessionFactoryOp
return delegate.isInitializeLazyStateOutsideTransactionsEnabled(); return delegate.isInitializeLazyStateOutsideTransactionsEnabled();
} }
@Override
public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() {
return delegate.getMultiTableBulkIdStrategy();
}
@Override @Override
public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() { public TempTableDdlTransactionHandling getTempTableDdlTransactionHandling() {
return delegate.getTempTableDdlTransactionHandling(); return delegate.getTempTableDdlTransactionHandling();

View File

@ -156,8 +156,6 @@ public interface SessionFactoryOptions {
boolean isInitializeLazyStateOutsideTransactionsEnabled(); boolean isInitializeLazyStateOutsideTransactionsEnabled();
MultiTableBulkIdStrategy getMultiTableBulkIdStrategy();
TempTableDdlTransactionHandling getTempTableDdlTransactionHandling(); TempTableDdlTransactionHandling getTempTableDdlTransactionHandling();
BatchFetchStyle getBatchFetchStyle(); BatchFetchStyle getBatchFetchStyle();

View File

@ -43,6 +43,7 @@ import org.hibernate.cfg.annotations.NamedEntityGraphDefinition;
import org.hibernate.boot.internal.NamedProcedureCallDefinitionImpl; import org.hibernate.boot.internal.NamedProcedureCallDefinitionImpl;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.hibernate.dialect.function.SQLFunction; import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.query.sql.spi.NamedNativeQueryMemento;
import org.hibernate.query.sql.spi.ResultSetMappingDescriptor; import org.hibernate.query.sql.spi.ResultSetMappingDescriptor;
import org.hibernate.query.hql.internal.NamedHqlQueryMementoImpl; import org.hibernate.query.hql.internal.NamedHqlQueryMementoImpl;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
@ -91,10 +92,10 @@ public class Configuration {
// used during processing mappings // used during processing mappings
private ImplicitNamingStrategy implicitNamingStrategy; private ImplicitNamingStrategy implicitNamingStrategy;
private PhysicalNamingStrategy physicalNamingStrategy; private PhysicalNamingStrategy physicalNamingStrategy;
private List<BasicType> basicTypes = new ArrayList<BasicType>(); private List<BasicType> basicTypes = new ArrayList<>();
private List<TypeContributor> typeContributorRegistrations = new ArrayList<TypeContributor>(); private List<TypeContributor> typeContributorRegistrations = new ArrayList<>();
private Map<String, NamedHqlQueryMementoImpl> namedQueries; private Map<String, NamedHqlQueryMementoImpl> namedQueries;
private Map<String, NamedSQLQueryDefinition> namedSqlQueries; private Map<String, NamedNativeQueryMemento> namedSqlQueries;
private Map<String, NamedProcedureCallDefinitionImpl> namedProcedureCallMap; private Map<String, NamedProcedureCallDefinitionImpl> namedProcedureCallMap;
private Map<String, ResultSetMappingDescriptor> sqlResultSetMappings; private Map<String, ResultSetMappingDescriptor> sqlResultSetMappings;
private Map<String, NamedEntityGraphDefinition> namedEntityGraphMap; private Map<String, NamedEntityGraphDefinition> namedEntityGraphMap;
@ -130,10 +131,10 @@ public class Configuration {
} }
private static BootstrapServiceRegistry getBootstrapRegistry(ServiceRegistry serviceRegistry) { private static BootstrapServiceRegistry getBootstrapRegistry(ServiceRegistry serviceRegistry) {
if ( BootstrapServiceRegistry.class.isInstance( serviceRegistry ) ) { if ( serviceRegistry instanceof BootstrapServiceRegistry ) {
return (BootstrapServiceRegistry) serviceRegistry; return (BootstrapServiceRegistry) serviceRegistry;
} }
else if ( StandardServiceRegistry.class.isInstance( serviceRegistry ) ) { else if ( serviceRegistry instanceof StandardServiceRegistry ) {
final StandardServiceRegistry ssr = (StandardServiceRegistry) serviceRegistry; final StandardServiceRegistry ssr = (StandardServiceRegistry) serviceRegistry;
return (BootstrapServiceRegistry) ssr.getParentServiceRegistry(); return (BootstrapServiceRegistry) ssr.getParentServiceRegistry();
} }
@ -148,11 +149,11 @@ public class Configuration {
protected void reset() { protected void reset() {
implicitNamingStrategy = ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; implicitNamingStrategy = ImplicitNamingStrategyJpaCompliantImpl.INSTANCE;
physicalNamingStrategy = PhysicalNamingStrategyStandardImpl.INSTANCE; physicalNamingStrategy = PhysicalNamingStrategyStandardImpl.INSTANCE;
namedQueries = new HashMap<String, NamedHqlQueryMementoImpl>(); namedQueries = new HashMap<>();
namedSqlQueries = new HashMap<String,NamedSQLQueryDefinition>(); namedSqlQueries = new HashMap<>();
sqlResultSetMappings = new HashMap<String, ResultSetMappingDescriptor>(); sqlResultSetMappings = new HashMap<>();
namedEntityGraphMap = new HashMap<String, NamedEntityGraphDefinition>(); namedEntityGraphMap = new HashMap<>();
namedProcedureCallMap = new HashMap<String, NamedProcedureCallDefinitionImpl>( ); namedProcedureCallMap = new HashMap<>();
standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry ); standardServiceRegistryBuilder = new StandardServiceRegistryBuilder( bootstrapServiceRegistry );
entityTuplizerFactory = new EntityTuplizerFactory(); entityTuplizerFactory = new EntityTuplizerFactory();

View File

@ -19,8 +19,6 @@ import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.RegionFactory;
import org.hibernate.cache.spi.TimestampsCacheFactory; import org.hibernate.cache.spi.TimestampsCacheFactory;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.loader.BatchFetchStyle; import org.hibernate.loader.BatchFetchStyle;
import org.hibernate.tuple.entity.EntityTuplizerFactory; import org.hibernate.tuple.entity.EntityTuplizerFactory;
@ -171,10 +169,6 @@ public final class Settings {
return sessionFactoryOptions.isInitializeLazyStateOutsideTransactionsEnabled(); return sessionFactoryOptions.isInitializeLazyStateOutsideTransactionsEnabled();
} }
public MultiTableBulkIdStrategy getMultiTableBulkIdStrategy() {
return sessionFactoryOptions.getMultiTableBulkIdStrategy();
}
public BatchFetchStyle getBatchFetchStyle() { public BatchFetchStyle getBatchFetchStyle() {
return sessionFactoryOptions.getBatchFetchStyle(); return sessionFactoryOptions.getBatchFetchStyle();
} }
@ -308,10 +302,6 @@ public final class Settings {
return sessionFactoryOptions.getServiceRegistry().getService( JtaPlatform.class ); return sessionFactoryOptions.getServiceRegistry().getService( JtaPlatform.class );
} }
public QueryTranslatorFactory getQueryTranslatorFactory() {
return sessionFactoryOptions.getServiceRegistry().getService( QueryTranslatorFactory.class );
}
public void setCheckNullability(boolean enabled) { public void setCheckNullability(boolean enabled) {
// ugh, used by org.hibernate.cfg.beanvalidation.TypeSafeActivator as part of the BV integrator // ugh, used by org.hibernate.cfg.beanvalidation.TypeSafeActivator as part of the BV integrator
sessionFactoryOptions.setCheckNullability( enabled ); sessionFactoryOptions.setCheckNullability( enabled );

View File

@ -32,7 +32,6 @@ import javax.persistence.OneToMany;
import org.hibernate.AnnotationException; import org.hibernate.AnnotationException;
import org.hibernate.FetchMode; import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.annotations.BatchSize; import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache; import org.hibernate.annotations.Cache;
@ -89,11 +88,9 @@ import org.hibernate.cfg.PropertyHolderBuilder;
import org.hibernate.cfg.PropertyInferredData; import org.hibernate.cfg.PropertyInferredData;
import org.hibernate.cfg.PropertyPreloadedData; import org.hibernate.cfg.PropertyPreloadedData;
import org.hibernate.cfg.SecondPass; import org.hibernate.cfg.SecondPass;
import org.hibernate.criterion.Junction;
import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.ConfigurationService;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.mapping.Any; import org.hibernate.mapping.Any;

View File

@ -33,13 +33,11 @@ public abstract class AbstractBagSemantics<B extends Collection<?>> implements C
} }
@Override @Override
@SuppressWarnings("unchecked") public Iterator getElementIterator(B rawCollection) {
public <E> Iterator<E> getElementIterator(B rawCollection) {
if ( rawCollection == null ) { if ( rawCollection == null ) {
return null; return null;
} }
return rawCollection.iterator();
return (Iterator<E>) rawCollection.iterator();
} }
@Override @Override

View File

@ -10,10 +10,10 @@ import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.CollectionSemantics; import org.hibernate.collection.spi.CollectionSemantics;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -52,7 +52,7 @@ public class StandardArraySemantics implements CollectionSemantics<Object[]> {
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentArrayHolder( key, session, collectionDescriptor ); return new PersistentArrayHolder( session, collectionDescriptor );
} }
@Override @Override
@ -60,13 +60,12 @@ public class StandardArraySemantics implements CollectionSemantics<Object[]> {
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentArrayHolder( session, collectionDescriptor, rawCollection ); return new PersistentArrayHolder( session, rawCollection );
} }
@Override @Override
@SuppressWarnings("unchecked") public Iterator getElementIterator(Object[] rawCollection) {
public <E> Iterator<E> getElementIterator(Object[] rawCollection) { return Arrays.stream( rawCollection ).iterator();
return (Iterator<E>) Arrays.stream( rawCollection ).iterator();
} }
@Override @Override

View File

@ -8,9 +8,9 @@ package org.hibernate.collection.internal;
import java.util.Collection; import java.util.Collection;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -37,16 +37,15 @@ public class StandardBagSemantics extends AbstractBagSemantics<Collection<?>> {
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentBag( session, collectionDescriptor ); return new PersistentBag( session );
} }
@Override @Override
@SuppressWarnings("unchecked") public PersistentCollection wrap(
public <E> PersistentCollection<E> wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentBag( session, collectionDescriptor, (Collection) rawCollection ); return new PersistentBag( session, (Collection) rawCollection );
} }
} }

View File

@ -7,10 +7,11 @@
package org.hibernate.collection.internal; package org.hibernate.collection.internal;
import java.util.Collection; import java.util.Collection;
import java.util.Iterator;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -33,20 +34,18 @@ public class StandardIdentifierBagSemantics<E> extends AbstractBagSemantics<Coll
} }
@Override @Override
@SuppressWarnings("unchecked") public PersistentCollection instantiateWrapper(
public PersistentCollection<E> instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentIdentifierBag( session, collectionDescriptor, key ); return new PersistentIdentifierBag( session );
} }
@Override @Override
@SuppressWarnings("unchecked") public PersistentCollection wrap(
public PersistentCollection<E> wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentIdentifierBag( session, collectionDescriptor, (Collection) rawCollection ); return new PersistentIdentifierBag( session, (Collection) rawCollection );
} }
} }

View File

@ -10,11 +10,11 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.CollectionSemantics; import org.hibernate.collection.spi.CollectionSemantics;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -44,7 +44,6 @@ public class StandardListSemantics implements CollectionSemantics<List> {
} }
@Override @Override
@SuppressWarnings("unchecked")
public Iterator getElementIterator(List rawCollection) { public Iterator getElementIterator(List rawCollection) {
return rawCollection.iterator(); return rawCollection.iterator();
} }
@ -60,15 +59,14 @@ public class StandardListSemantics implements CollectionSemantics<List> {
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentList( session, collectionDescriptor, key ); return new PersistentList( session );
} }
@Override @Override
@SuppressWarnings("unchecked") public PersistentCollection wrap(
public <E> PersistentCollection<E> wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentList( session, collectionDescriptor, (List) rawCollection ); return new PersistentList( session, (List) rawCollection );
} }
} }

View File

@ -8,10 +8,10 @@ package org.hibernate.collection.internal;
import java.util.Map; import java.util.Map;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -41,18 +41,18 @@ public class StandardMapSemantics extends AbstractMapSemantics<Map<?,?>> {
} }
@Override @Override
public <E> PersistentCollection<E> instantiateWrapper( public PersistentCollection instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentMap( session, collectionDescriptor, key ); return new PersistentMap( session );
} }
@Override @Override
public <E> PersistentCollection<E> wrap( public PersistentCollection wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentMap( session, collectionDescriptor, (Map) rawCollection ); return new PersistentMap( session, (Map) rawCollection );
} }
} }

View File

@ -10,10 +10,10 @@ import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
@ -35,24 +35,24 @@ public class StandardOrderedMapSemantics extends AbstractMapSemantics<LinkedHash
@Override @Override
public LinkedHashMap<?, ?> instantiateRaw( public LinkedHashMap<?, ?> instantiateRaw(
int anticipatedSize, int anticipatedSize,
PersistentCollectionDescriptor collectionDescriptor) { CollectionPersister collectionDescriptor) {
return anticipatedSize < 1 ? new LinkedHashMap<>() : new LinkedHashMap<>( anticipatedSize ); return anticipatedSize < 1 ? new LinkedHashMap<>() : new LinkedHashMap<>( anticipatedSize );
} }
@Override @Override
public <E> PersistentCollection<E> instantiateWrapper( public PersistentCollection instantiateWrapper(
Object key, Object key,
PersistentCollectionDescriptor<?, LinkedHashMap<?, ?>, E> collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentMap<>( session, collectionDescriptor, key ); return new PersistentMap( session );
} }
@Override @Override
public <E> PersistentCollection<E> wrap( public PersistentCollection wrap(
Object rawCollection, Object rawCollection,
PersistentCollectionDescriptor<?, LinkedHashMap<?, ?>, E> collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentMap<>( session, collectionDescriptor, (Map) rawCollection ); return new PersistentMap( session, (Map) rawCollection );
} }
@Override @Override

View File

@ -10,10 +10,10 @@ import java.util.Iterator;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.model.mapping.PersistentCollectionDescriptor; import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister;
/** /**
* @author Steve Ebersole * @author Steve Ebersole
@ -35,24 +35,24 @@ public class StandardOrderedSetSemantics extends AbstractSetSemantics<LinkedHash
@Override @Override
public LinkedHashSet<?> instantiateRaw( public LinkedHashSet<?> instantiateRaw(
int anticipatedSize, int anticipatedSize,
PersistentCollectionDescriptor collectionDescriptor) { CollectionPersister collectionDescriptor) {
return anticipatedSize < 1 ? new LinkedHashSet() : new LinkedHashSet<>( anticipatedSize ); return anticipatedSize < 1 ? new LinkedHashSet() : new LinkedHashSet<>( anticipatedSize );
} }
@Override @Override
public <E> PersistentCollection<E> instantiateWrapper( public PersistentCollection instantiateWrapper(
Object key, Object key,
PersistentCollectionDescriptor<?, LinkedHashSet<?>, E> collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSet( session, collectionDescriptor, key ); return new PersistentSet( session );
} }
@Override @Override
public <E> PersistentCollection<E> wrap( public PersistentCollection wrap(
Object rawCollection, Object rawCollection,
PersistentCollectionDescriptor<?, LinkedHashSet<?>, E> collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSet( session, collectionDescriptor, (Set) rawCollection ); return new PersistentSet( session, (Set) rawCollection );
} }
@Override @Override

View File

@ -9,9 +9,8 @@ package org.hibernate.collection.internal;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -39,21 +38,19 @@ public class StandardSetSemantics extends AbstractSetSemantics<Set<?>> {
} }
@Override @Override
public <E> PersistentCollection<E> instantiateWrapper( public PersistentSet instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
//noinspection unchecked return new PersistentSet( session );
return new PersistentSet( session, collectionDescriptor, key );
} }
@Override @Override
public <E> PersistentCollection<E> wrap( public PersistentSet wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
//noinspection unchecked return new PersistentSet( session, (Set) rawCollection );
return new PersistentSet( session, collectionDescriptor, (Set) rawCollection );
} }
} }

View File

@ -9,9 +9,9 @@ package org.hibernate.collection.internal;
import java.util.SortedMap; import java.util.SortedMap;
import java.util.TreeMap; import java.util.TreeMap;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -35,24 +35,22 @@ public class StandardSortedMapSemantics extends AbstractMapSemantics<SortedMap<?
public TreeMap<?, ?> instantiateRaw( public TreeMap<?, ?> instantiateRaw(
int anticipatedSize, int anticipatedSize,
CollectionPersister collectionDescriptor) { CollectionPersister collectionDescriptor) {
return new TreeMap<>( collectionDescriptor.getSortingComparator() ); return new TreeMap( collectionDescriptor.getSortingComparator() );
} }
@Override @Override
@SuppressWarnings("unchecked")
public PersistentCollection instantiateWrapper( public PersistentCollection instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSortedMap( session, collectionDescriptor, key ); return new PersistentSortedMap( session );
} }
@Override @Override
@SuppressWarnings("unchecked")
public PersistentCollection wrap( public PersistentCollection wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSortedMap( session, collectionDescriptor, (SortedMap) rawCollection ); return new PersistentSortedMap( session, (SortedMap) rawCollection );
} }
} }

View File

@ -10,9 +10,9 @@ import java.util.Iterator;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import org.hibernate.collection.spi.CollectionClassification;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.metamodel.CollectionClassification;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
/** /**
@ -36,30 +36,27 @@ public class StandardSortedSetSemantics extends AbstractSetSemantics<SortedSet<?
public SortedSet instantiateRaw( public SortedSet instantiateRaw(
int anticipatedSize, int anticipatedSize,
CollectionPersister collectionDescriptor) { CollectionPersister collectionDescriptor) {
return new TreeSet<>( collectionDescriptor.getSortingComparator() ); return new TreeSet( collectionDescriptor.getSortingComparator() );
} }
@Override @Override
@SuppressWarnings("unchecked")
public PersistentCollection instantiateWrapper( public PersistentCollection instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSortedSet( session, collectionDescriptor, key ); return new PersistentSortedSet( session );
} }
@Override @Override
@SuppressWarnings("unchecked")
public PersistentCollection wrap( public PersistentCollection wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session) { SharedSessionContractImplementor session) {
return new PersistentSortedSet( session, collectionDescriptor, (SortedSet) rawCollection ); return new PersistentSortedSet( session, (SortedSet) rawCollection );
} }
@Override @Override
@SuppressWarnings("unchecked") public Iterator getElementIterator(SortedSet<?> rawCollection) {
public <E> Iterator<E> getElementIterator(SortedSet<?> rawCollection) { return rawCollection.iterator();
return (Iterator<E>) rawCollection.iterator();
} }
} }

View File

@ -28,21 +28,21 @@ public interface CollectionSemantics<C> {
*/ */
CollectionClassification getCollectionClassification(); CollectionClassification getCollectionClassification();
<E> C instantiateRaw( C instantiateRaw(
int anticipatedSize, int anticipatedSize,
CollectionPersister collectionDescriptor); CollectionPersister collectionDescriptor);
<E> PersistentCollection instantiateWrapper( PersistentCollection instantiateWrapper(
Object key, Object key,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session); SharedSessionContractImplementor session);
<E> PersistentCollection wrap( PersistentCollection wrap(
Object rawCollection, Object rawCollection,
CollectionPersister collectionDescriptor, CollectionPersister collectionDescriptor,
SharedSessionContractImplementor session); SharedSessionContractImplementor session);
<E> Iterator<E> getElementIterator(C rawCollection); Iterator getElementIterator(C rawCollection);
void visitElements(C rawCollection, Consumer action); void visitElements(C rawCollection, Consumer action);
} }

View File

@ -24,10 +24,6 @@ import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.identity.AbstractTransactSQLIdentityColumnSupport; import org.hibernate.dialect.identity.AbstractTransactSQLIdentityColumnSupport;
import org.hibernate.dialect.identity.IdentityColumnSupport; import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
/** /**

View File

@ -37,10 +37,6 @@ import org.hibernate.exception.internal.CacheSQLExceptionConversionDelegate;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.sql.CacheJoinFragment; import org.hibernate.sql.CacheJoinFragment;
import org.hibernate.sql.JoinFragment; import org.hibernate.sql.JoinFragment;

View File

@ -9,10 +9,6 @@ package org.hibernate.dialect;
import java.sql.Types; import java.sql.Types;
import org.hibernate.dialect.function.DB2SubstringFunction; import org.hibernate.dialect.function.DB2SubstringFunction;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.type.descriptor.sql.CharTypeDescriptor; import org.hibernate.type.descriptor.sql.CharTypeDescriptor;
import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; import org.hibernate.type.descriptor.sql.ClobTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;

View File

@ -21,10 +21,6 @@ import org.hibernate.dialect.pagination.LimitHelper;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelper; import org.hibernate.engine.jdbc.env.spi.IdentifierHelper;
import org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder; import org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder;
import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.RowSelection;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.sql.CaseFragment; import org.hibernate.sql.CaseFragment;

View File

@ -29,10 +29,6 @@ import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;

View File

@ -9,10 +9,6 @@ package org.hibernate.dialect;
import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
/** /**

View File

@ -6,11 +6,6 @@
*/ */
package org.hibernate.dialect; package org.hibernate.dialect;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
/** /**
* An SQL dialect for the SAP HANA row store. * An SQL dialect for the SAP HANA row store.
* <p> * <p>

View File

@ -40,11 +40,6 @@ import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;

View File

@ -23,10 +23,6 @@ import org.hibernate.dialect.unique.InformixUniqueDelegate;
import org.hibernate.dialect.unique.UniqueDelegate; import org.hibernate.dialect.unique.UniqueDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorInformixDatabaseImpl; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorInformixDatabaseImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;

View File

@ -16,10 +16,6 @@ import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.pagination.FirstLimitHandler; import org.hibernate.dialect.pagination.FirstLimitHandler;
import org.hibernate.dialect.pagination.LegacyFirstLimitHandler; import org.hibernate.dialect.pagination.LegacyFirstLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.tool.schema.extract.internal.SequenceNameExtractorImpl; import org.hibernate.tool.schema.extract.internal.SequenceNameExtractorImpl;
import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor; import org.hibernate.tool.schema.extract.spi.SequenceInformationExtractor;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;

View File

@ -31,10 +31,6 @@ import org.hibernate.engine.spi.RowSelection;
import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.LockTimeoutException; import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;

View File

@ -25,6 +25,7 @@ import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.pagination.AbstractLimitHandler; import org.hibernate.dialect.pagination.AbstractLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.LimitHelper; import org.hibernate.dialect.pagination.LimitHelper;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.RowSelection;
import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.LockAcquisitionException;
@ -32,10 +33,6 @@ import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.procedure.internal.StandardCallableStatementSupport; import org.hibernate.procedure.internal.StandardCallableStatementSupport;
import org.hibernate.procedure.spi.CallableStatementSupport; import org.hibernate.procedure.spi.CallableStatementSupport;

View File

@ -14,10 +14,6 @@ import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorOracleDatabaseImpl; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorOracleDatabaseImpl;

View File

@ -34,10 +34,6 @@ import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.internal.util.JdbcExceptionHelper;
import org.hibernate.procedure.internal.PostgresCallableStatementSupport; import org.hibernate.procedure.internal.PostgresCallableStatementSupport;
import org.hibernate.procedure.spi.CallableStatementSupport; import org.hibernate.procedure.spi.CallableStatementSupport;

View File

@ -7,10 +7,6 @@
package org.hibernate.dialect; package org.hibernate.dialect;
import org.hibernate.boot.model.TypeContributions; import org.hibernate.boot.model.TypeContributions;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.PostgresUUIDType; import org.hibernate.type.PostgresUUIDType;

View File

@ -14,10 +14,6 @@ import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.sql.CaseFragment; import org.hibernate.sql.CaseFragment;
import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.sql.DecodeCaseFragment;
import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorSAPDBDatabaseImpl; import org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorSAPDBDatabaseImpl;

View File

@ -22,6 +22,7 @@ import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.identity.IdentityColumnSupport; import org.hibernate.dialect.identity.IdentityColumnSupport;
import org.hibernate.dialect.identity.Teradata14IdentityColumnSupport; import org.hibernate.dialect.identity.Teradata14IdentityColumnSupport;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter;
import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter;
import org.hibernate.mapping.Column; import org.hibernate.mapping.Column;

View File

@ -11,11 +11,6 @@ import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.VarArgsSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.hql.spi.id.IdTableSupport;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.StandardBasicTypes;
/** /**
@ -24,7 +19,7 @@ import org.hibernate.type.StandardBasicTypes;
* *
* @author Jay Nance * @author Jay Nance
*/ */
public class TeradataDialect extends Dialect implements IdTableSupport { public class TeradataDialect extends Dialect {
private static final int PARAM_LIST_SIZE_LIMIT = 1024; private static final int PARAM_LIST_SIZE_LIMIT = 1024;

View File

@ -23,10 +23,6 @@ import org.hibernate.dialect.lock.UpdateLockingStrategy;
import org.hibernate.dialect.pagination.FirstLimitHandler; import org.hibernate.dialect.pagination.FirstLimitHandler;
import org.hibernate.dialect.pagination.LegacyFirstLimitHandler; import org.hibernate.dialect.pagination.LegacyFirstLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.persister.entity.Lockable; import org.hibernate.persister.entity.Lockable;
import org.hibernate.sql.JoinFragment; import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.OracleJoinFragment; import org.hibernate.sql.OracleJoinFragment;

View File

@ -1,14 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.ejb;
/**
* @deprecated Use {@link org.hibernate.jpa.HibernateQuery} instead
*/
@Deprecated
public interface HibernateQuery extends org.hibernate.jpa.HibernateQuery {
}

View File

@ -12,6 +12,7 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;

View File

@ -40,7 +40,6 @@ import org.hibernate.bytecode.enhance.spi.interceptor.LazyAttributeLoadingInterc
import org.hibernate.cache.spi.access.NaturalIdDataAccess; import org.hibernate.cache.spi.access.NaturalIdDataAccess;
import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.cache.spi.access.SoftLock;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.loading.internal.LoadContexts;
import org.hibernate.engine.spi.AssociationKey; import org.hibernate.engine.spi.AssociationKey;
import org.hibernate.engine.spi.BatchFetchQueue; import org.hibernate.engine.spi.BatchFetchQueue;
import org.hibernate.engine.spi.CachedNaturalIdValueSource; import org.hibernate.engine.spi.CachedNaturalIdValueSource;
@ -67,6 +66,7 @@ import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer; import org.hibernate.proxy.LazyInitializer;
import org.hibernate.sql.results.spi.LoadContexts;
import org.hibernate.stat.internal.StatsHelper; import org.hibernate.stat.internal.StatsHelper;
import org.hibernate.stat.spi.StatisticsImplementor; import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.type.CollectionType; import org.hibernate.type.CollectionType;
@ -937,7 +937,7 @@ public class StatefulPersistenceContext implements PersistenceContext {
} }
@Override @Override
public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Object id)
throws HibernateException { throws HibernateException {
final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing ); final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing );
ce.postInitialize( collection ); ce.postInitialize( collection );

View File

@ -1,431 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.loading.internal;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.CacheMode;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.bytecode.spi.BytecodeEnhancementMetadata;
import org.hibernate.cache.spi.access.CollectionDataAccess;
import org.hibernate.cache.spi.entry.CollectionCacheEntry;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.Status;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.collection.QueryableCollection;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.stat.spi.StatisticsImplementor;
/**
* Represents state associated with the processing of a given {@link ResultSet}
* in regards to loading collections.
* <p/>
* Another implementation option to consider is to not expose {@link ResultSet}s
* directly (in the JDBC redesign) but to always "wrap" them and apply a
* [series of] context[s] to that wrapper.
*
* @author Steve Ebersole
*/
public class CollectionLoadContext {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( CollectionLoadContext.class );
private final LoadContexts loadContexts;
private final ResultSet resultSet;
private Set<CollectionKey> localLoadingCollectionKeys = new HashSet<>();
/**
* Creates a collection load context for the given result set.
*
* @param loadContexts Callback to other collection load contexts.
* @param resultSet The result set this is "wrapping".
*/
public CollectionLoadContext(LoadContexts loadContexts, ResultSet resultSet) {
this.loadContexts = loadContexts;
this.resultSet = resultSet;
}
public ResultSet getResultSet() {
return resultSet;
}
public LoadContexts getLoadContext() {
return loadContexts;
}
/**
* Retrieve the collection that is being loaded as part of processing this
* result set.
* <p/>
* Basically, there are two valid return values from this method:<ul>
* <li>an instance of {@link org.hibernate.collection.spi.PersistentCollection} which indicates to
* continue loading the result set row data into that returned collection
* instance; this may be either an instance already associated and in the
* midst of being loaded, or a newly instantiated instance as a matching
* associated collection was not found.</li>
* <li><i>null</i> indicates to ignore the corresponding result set row
* data relating to the requested collection; this indicates that either
* the collection was found to already be associated with the persistence
* context in a fully loaded state, or it was found in a loading state
* associated with another result set processing context.</li>
* </ul>
*
* @param persister The persister for the collection being requested.
* @param key The key of the collection being requested.
*
* @return The loading collection (see discussion above).
*/
public PersistentCollection getLoadingCollection(final CollectionPersister persister, final Serializable key) {
final CollectionKey collectionKey = new CollectionKey( persister, key );
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Starting attempt to find loading collection [{0}]",
MessageHelper.collectionInfoString( persister.getRole(), key ) );
}
final LoadingCollectionEntry loadingCollectionEntry = loadContexts.locateLoadingCollectionEntry( collectionKey );
if ( loadingCollectionEntry == null ) {
// look for existing collection as part of the persistence context
PersistentCollection collection = loadContexts.getPersistenceContext().getCollection( collectionKey );
if ( collection != null ) {
if ( collection.wasInitialized() ) {
LOG.trace( "Collection already initialized; ignoring" );
// ignore this row of results! Note the early exit
return null;
}
LOG.trace( "Collection not yet initialized; initializing" );
}
else {
final Object owner = loadContexts.getPersistenceContext().getCollectionOwner( key, persister );
final boolean newlySavedEntity = owner != null
&& loadContexts.getPersistenceContext().getEntry( owner ).getStatus() != Status.LOADING;
if ( newlySavedEntity ) {
// important, to account for newly saved entities in query
// todo : some kind of check for new status...
LOG.trace( "Owning entity already loaded; ignoring" );
return null;
}
// create one
LOG.tracev( "Instantiating new collection [key={0}, rs={1}]", key, resultSet );
collection = persister.getCollectionType().instantiate(
loadContexts.getPersistenceContext().getSession(), persister, key );
}
collection.beforeInitialize( persister, -1 );
collection.beginRead();
localLoadingCollectionKeys.add( collectionKey );
loadContexts.registerLoadingCollectionXRef( collectionKey, new LoadingCollectionEntry( resultSet, persister, key, collection ) );
return collection;
}
if ( loadingCollectionEntry.getResultSet() == resultSet ) {
LOG.trace( "Found loading collection bound to current result set processing; reading row" );
return loadingCollectionEntry.getCollection();
}
// ignore this row, the collection is in process of
// being loaded somewhere further "up" the stack
LOG.trace( "Collection is already being initialized; ignoring row" );
return null;
}
/**
* Finish the process of collection-loading for this bound result set. Mainly this
* involves cleaning up resources and notifying the collections that loading is
* complete.
*
* @param persister The persister for which to complete loading.
*/
public void endLoadingCollections(CollectionPersister persister) {
final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
if ( !loadContexts.hasLoadingCollectionEntries()
&& localLoadingCollectionKeys.isEmpty() ) {
return;
}
// in an effort to avoid concurrent-modification-exceptions (from
// potential recursive calls back through here as a result of the
// eventual call to PersistentCollection#endRead), we scan the
// internal loadingCollections map for matches and store those matches
// in a temp collection. the temp collection is then used to "drive"
// the #endRead processing.
List<LoadingCollectionEntry> matches = null;
final Iterator itr = localLoadingCollectionKeys.iterator();
final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
while ( itr.hasNext() ) {
final CollectionKey collectionKey = (CollectionKey) itr.next();
final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry( collectionKey );
if ( lce == null ) {
LOG.loadingCollectionKeyNotFound( collectionKey );
}
else if ( lce.getResultSet() == resultSet && lce.getPersister() == persister ) {
if ( matches == null ) {
matches = new ArrayList<>();
}
matches.add( lce );
if ( lce.getCollection().getOwner() == null ) {
persistenceContext.addUnownedCollection(
new CollectionKey(
persister,
lce.getKey()
),
lce.getCollection()
);
}
LOG.tracev( "Removing collection load entry [{0}]", lce );
// todo : i'd much rather have this done from #endLoadingCollection(CollectionPersister,LoadingCollectionEntry)...
loadContexts.unregisterLoadingCollectionXRef( collectionKey );
itr.remove();
}
}
endLoadingCollections( persister, matches );
if ( localLoadingCollectionKeys.isEmpty() ) {
// todo : hack!!!
// NOTE : here we cleanup the load context when we have no more local
// LCE entries. This "works" for the time being because really
// only the collection load contexts are implemented. Long term,
// this cleanup should become part of the "close result set"
// processing from the (sandbox/jdbc) jdbc-container code.
loadContexts.cleanup( resultSet );
}
}
private void endLoadingCollections(CollectionPersister persister, List<LoadingCollectionEntry> matchedCollectionEntries) {
if ( matchedCollectionEntries == null ) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "No collections were found in result set for role: %s", persister.getRole() );
}
return;
}
final int count = matchedCollectionEntries.size();
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "%s collections were found in result set for role: %s", count, persister.getRole() );
}
for ( LoadingCollectionEntry matchedCollectionEntry : matchedCollectionEntries ) {
endLoadingCollection( matchedCollectionEntry, persister );
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "%s collections initialized for role: %s", count, persister.getRole() );
}
}
private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
LOG.tracev( "Ending loading collection [{0}]", lce );
final PersistenceContext persistenceContext = getLoadContext().getPersistenceContext();
final SharedSessionContractImplementor session = persistenceContext.getSession();
// warning: can cause a recursive calls! (proxy initialization)
final PersistentCollection loadingCollection = lce.getCollection();
final boolean hasNoQueuedAdds = loadingCollection.endRead();
if ( persister.getCollectionType().hasHolder() ) {
persistenceContext.addCollectionHolder( loadingCollection );
}
CollectionEntry ce = persistenceContext.getCollectionEntry( loadingCollection );
if ( ce == null ) {
ce = persistenceContext.addInitializedCollection( persister, loadingCollection, lce.getKey() );
}
else {
ce.postInitialize( loadingCollection );
// if (ce.getLoadedPersister().getBatchSize() > 1) { // not the best place for doing this, moved into ce.postInitialize
// getLoadContext().getPersistenceContext().getBatchFetchQueue().removeBatchLoadableCollection(ce);
// }
}
// The collection has been completely initialized and added to the PersistenceContext.
if ( loadingCollection.getOwner() != null ) {
// If the owner is bytecode-enhanced and the owner's collection value is uninitialized,
// then go ahead and set it to the newly initialized collection.
final EntityPersister ownerEntityPersister = persister.getOwnerEntityPersister();
final BytecodeEnhancementMetadata bytecodeEnhancementMetadata =
ownerEntityPersister.getBytecodeEnhancementMetadata();
if ( bytecodeEnhancementMetadata.isEnhancedForLazyLoading() ) {
// Lazy properties in embeddables/composites are not currently supported for embeddables (HHH-10480),
// so check to make sure the collection is not in an embeddable before checking to see if
// the collection is lazy.
// TODO: More will probably need to be done here when HHH-10480 is fixed..
if ( StringHelper.qualifier( persister.getRole() ).length() ==
ownerEntityPersister.getEntityName().length() ) {
// Assume the collection is not in an embeddable.
// Strip off <entityName><dot> to get the collection property name.
final String propertyName = persister.getRole().substring(
ownerEntityPersister.getEntityName().length() + 1
);
if ( !bytecodeEnhancementMetadata.isAttributeLoaded( loadingCollection.getOwner(), propertyName ) ) {
int propertyIndex = ownerEntityPersister.getEntityMetamodel().getPropertyIndex(
propertyName
);
ownerEntityPersister.setPropertyValue(
loadingCollection.getOwner(),
propertyIndex,
loadingCollection
);
}
}
}
}
// add to cache if:
boolean addToCache =
// there were no queued additions
hasNoQueuedAdds
// and the role has a cache
&& persister.hasCache()
// and this is not a forced initialization during flush
&& session.getCacheMode().isPutEnabled() && !ce.isDoremove();
if ( addToCache ) {
addCollectionToCache( lce, persister );
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Collection fully initialized: %s",
MessageHelper.collectionInfoString( persister, loadingCollection, lce.getKey(), session )
);
}
final StatisticsImplementor statistics = session.getFactory().getStatistics();
if ( statistics.isStatisticsEnabled() ) {
statistics.loadCollection( persister.getRole() );
}
}
/**
* Add the collection to the second-level cache
*
* @param lce The entry representing the collection to add
* @param persister The persister
*/
private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
final PersistenceContext persistenceContext = getLoadContext().getPersistenceContext();
final SharedSessionContractImplementor session = persistenceContext.getSession();
final SessionFactoryImplementor factory = session.getFactory();
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Caching collection: %s", MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) );
}
if ( session.getLoadQueryInfluencers().hasEnabledFilters() && persister.isAffectedByEnabledFilters( session ) ) {
// some filters affecting the collection are enabled on the session, so do not do the put into the cache.
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Refusing to add to cache due to enabled filters" );
}
// todo : add the notion of enabled filters to the cache key to differentiate filtered collections from non-filtered;
// DefaultInitializeCollectionEventHandler.initializeCollectionFromCache() (which makes sure to not read from
// cache with enabled filters).
// EARLY EXIT!!!!!
return;
}
final Object version;
if ( persister.isVersioned() ) {
Object collectionOwner = persistenceContext.getCollectionOwner( lce.getKey(), persister );
if ( collectionOwner == null ) {
// generally speaking this would be caused by the collection key being defined by a property-ref, thus
// the collection key and the owner key would not match up. In this case, try to use the key of the
// owner instance associated with the collection itself, if one. If the collection does already know
// about its owner, that owner should be the same instance as associated with the PC, but we do the
// resolution against the PC anyway just to be safe since the lookup should not be costly.
if ( lce.getCollection() != null ) {
final Object linkedOwner = lce.getCollection().getOwner();
if ( linkedOwner != null ) {
final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier( linkedOwner, session );
collectionOwner = persistenceContext.getCollectionOwner( ownerKey, persister );
}
}
if ( collectionOwner == null ) {
throw new HibernateException(
"Unable to resolve owner of loading collection [" +
MessageHelper.collectionInfoString( persister, lce.getCollection(), lce.getKey(), session ) +
"] for second level caching"
);
}
}
version = persistenceContext.getEntry( collectionOwner ).getVersion();
}
else {
version = null;
}
final CollectionCacheEntry entry = new CollectionCacheEntry( lce.getCollection(), persister );
final CollectionDataAccess cacheAccess = persister.getCacheAccessStrategy();
final Object cacheKey = cacheAccess.generateCacheKey(
lce.getKey(),
persister,
session.getFactory(),
session.getTenantIdentifier()
);
boolean isPutFromLoad = true;
if ( persister.getElementType().isAssociationType() ) {
for ( Serializable id : entry.getState() ) {
EntityPersister entityPersister = ( (QueryableCollection) persister ).getElementPersister();
if ( persistenceContext.wasInsertedDuringTransaction( entityPersister, id ) ) {
isPutFromLoad = false;
break;
}
}
}
// CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
if (isPutFromLoad) {
final SessionEventListenerManager eventListenerManager = session.getEventListenerManager();
try {
eventListenerManager.cachePutStart();
final boolean put = cacheAccess.putFromLoad(
session,
cacheKey,
persister.getCacheEntryStructure().structure( entry ),
version,
factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode()!= CacheMode.REFRESH
);
final StatisticsImplementor statistics = factory.getStatistics();
if ( put && statistics.isStatisticsEnabled() ) {
statistics.collectionCachePut(
persister.getNavigableRole(),
persister.getCacheAccessStrategy().getRegion().getName()
);
}
}
finally {
eventListenerManager.cachePutEnd();
}
}
}
void cleanup() {
if ( !localLoadingCollectionKeys.isEmpty() ) {
LOG.localLoadingCollectionKeysCount( localLoadingCollectionKeys.size() );
}
loadContexts.cleanupCollectionXRefs( localLoadingCollectionKeys );
localLoadingCollectionKeys.clear();
}
@Override
public String toString() {
return super.toString() + "<rs=" + resultSet + ">";
}
}

View File

@ -1,47 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.loading.internal;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.Logger;
/**
* Tracks information about loading of entities specific to a given result set. These can be hierarchical.
*
* @author Steve Ebersole
*/
public class EntityLoadContext {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EntityLoadContext.class.getName() );
private final LoadContexts loadContexts;
private final ResultSet resultSet;
// todo : need map? the prob is a proper key, right?
private final List hydratingEntities = new ArrayList( 20 );
public EntityLoadContext(LoadContexts loadContexts, ResultSet resultSet) {
this.loadContexts = loadContexts;
this.resultSet = resultSet;
}
void cleanup() {
if ( !hydratingEntities.isEmpty() ) {
LOG.hydratingEntitiesCount( hydratingEntities.size() );
}
hydratingEntities.clear();
}
@Override
public String toString() {
return super.toString() + "<rs=" + resultSet + ">";
}
}

View File

@ -1,292 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.loading.internal;
import java.io.Serializable;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
/**
* Maps {@link ResultSet result-sets} to specific contextual data related to processing that result set
* <p/>
* Considering the JDBC-redesign work, would further like this contextual info not mapped separately, but available
* based on the result set being processed. This would also allow maintaining a single mapping as we could reliably
* get notification of the result-set closing...
*
* @author Steve Ebersole
*/
public class LoadContexts {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( LoadContexts.class );
private final PersistenceContext persistenceContext;
private Map<ResultSet,CollectionLoadContext> collectionLoadContexts;
private Map<ResultSet,EntityLoadContext> entityLoadContexts;
private Map<CollectionKey,LoadingCollectionEntry> xrefLoadingCollectionEntries;
/**
* Creates and binds this to the given persistence context.
*
* @param persistenceContext The persistence context to which this
* will be bound.
*/
public LoadContexts(PersistenceContext persistenceContext) {
this.persistenceContext = persistenceContext;
}
/**
* Retrieves the persistence context to which this is bound.
*
* @return The persistence context to which this is bound.
*/
public PersistenceContext getPersistenceContext() {
return persistenceContext;
}
private SharedSessionContractImplementor getSession() {
return getPersistenceContext().getSession();
}
// cleanup code ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Release internal state associated with the given result set.
* <p/>
* This should be called when we are done with processing said result set,
* ideally as the result set is being closed.
*
* @param resultSet The result set for which it is ok to release
* associated resources.
*/
public void cleanup(ResultSet resultSet) {
if ( collectionLoadContexts != null ) {
final CollectionLoadContext collectionLoadContext = collectionLoadContexts.remove( resultSet );
collectionLoadContext.cleanup();
}
if ( entityLoadContexts != null ) {
final EntityLoadContext entityLoadContext = entityLoadContexts.remove( resultSet );
entityLoadContext.cleanup();
}
}
/**
* Release internal state associated with *all* result sets.
* <p/>
* This is intended as a "failsafe" process to make sure we get everything
* cleaned up and released.
*/
public void cleanup() {
if ( collectionLoadContexts != null ) {
for ( CollectionLoadContext collectionLoadContext : collectionLoadContexts.values() ) {
LOG.failSafeCollectionsCleanup( collectionLoadContext );
collectionLoadContext.cleanup();
}
collectionLoadContexts.clear();
}
if ( entityLoadContexts != null ) {
for ( EntityLoadContext entityLoadContext : entityLoadContexts.values() ) {
LOG.failSafeEntitiesCleanup( entityLoadContext );
entityLoadContext.cleanup();
}
entityLoadContexts.clear();
}
}
// Collection load contexts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Do we currently have any internal entries corresponding to loading
* collections?
*
* @return True if we currently hold state pertaining to loading collections;
* false otherwise.
*/
public boolean hasLoadingCollectionEntries() {
return ( collectionLoadContexts != null && !collectionLoadContexts.isEmpty() );
}
/**
* Do we currently have any registered internal entries corresponding to loading
* collections?
*
* @return True if we currently hold state pertaining to a registered loading collections;
* false otherwise.
*/
public boolean hasRegisteredLoadingCollectionEntries() {
return ( xrefLoadingCollectionEntries != null && !xrefLoadingCollectionEntries.isEmpty() );
}
/**
* Get the {@link CollectionLoadContext} associated with the given
* {@link ResultSet}, creating one if needed.
*
* @param resultSet The result set for which to retrieve the context.
* @return The processing context.
*/
public CollectionLoadContext getCollectionLoadContext(ResultSet resultSet) {
CollectionLoadContext context = null;
if ( collectionLoadContexts == null ) {
collectionLoadContexts = new IdentityHashMap<ResultSet, CollectionLoadContext>( 8 );
}
else {
context = collectionLoadContexts.get(resultSet);
}
if ( context == null ) {
LOG.tracev( "Constructing collection load context for result set [{0}]", resultSet );
context = new CollectionLoadContext( this, resultSet );
collectionLoadContexts.put( resultSet, context );
}
return context;
}
/**
* Attempt to locate the loading collection given the CollectionKey obtained from the owner's key. The lookup here
* occurs against all result-set contexts...
*
* @param persister The collection persister
* @param key The collection key
* @return The loading collection, or null if not found.
*/
public PersistentCollection locateLoadingCollection(CollectionPersister persister, CollectionKey key) {
final LoadingCollectionEntry lce = locateLoadingCollectionEntry( key ) ;
if ( lce != null ) {
if ( LOG.isTraceEnabled() ) {
LOG.tracef(
"Returning loading collection: %s",
MessageHelper.collectionInfoString( persister, key.getKey(), getSession().getFactory() )
);
}
return lce.getCollection();
}
return null;
}
// loading collection xrefs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Register a loading collection xref.
* <p/>
* This xref map is used because sometimes a collection is in process of
* being loaded from one result set, but needs to be accessed from the
* context of another "nested" result set processing.
* <p/>
* Implementation note: package protected, as this is meant solely for use
* by {@link CollectionLoadContext} to be able to locate collections
* being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s.
*
* @param entryKey The xref collection key
* @param entry The corresponding loading collection entry
*/
void registerLoadingCollectionXRef(CollectionKey entryKey, LoadingCollectionEntry entry) {
if ( xrefLoadingCollectionEntries == null ) {
xrefLoadingCollectionEntries = new HashMap<CollectionKey,LoadingCollectionEntry>();
}
xrefLoadingCollectionEntries.put( entryKey, entry );
}
/**
* The inverse of {@link #registerLoadingCollectionXRef}. Here, we are done
* processing the said collection entry, so we remove it from the
* load context.
* <p/>
* The idea here is that other loading collections can now reference said
* collection directly from the {@link PersistenceContext} because it
* has completed its load cycle.
* <p/>
* Implementation note: package protected, as this is meant solely for use
* by {@link CollectionLoadContext} to be able to locate collections
* being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s.
*
* @param key The key of the collection we are done processing.
*/
void unregisterLoadingCollectionXRef(CollectionKey key) {
if ( !hasRegisteredLoadingCollectionEntries() ) {
return;
}
xrefLoadingCollectionEntries.remove( key );
}
@SuppressWarnings( {"UnusedDeclaration"})
Map getLoadingCollectionXRefs() {
return xrefLoadingCollectionEntries;
}
/**
* Locate the LoadingCollectionEntry within *any* of the tracked
* {@link CollectionLoadContext}s.
* <p/>
* Implementation note: package protected, as this is meant solely for use
* by {@link CollectionLoadContext} to be able to locate collections
* being loaded by other {@link CollectionLoadContext}s/{@link ResultSet}s.
*
* @param key The collection key.
* @return The located entry; or null.
*/
LoadingCollectionEntry locateLoadingCollectionEntry(CollectionKey key) {
if ( xrefLoadingCollectionEntries == null ) {
return null;
}
LOG.tracev( "Attempting to locate loading collection entry [{0}] in any result-set context", key );
final LoadingCollectionEntry rtn = xrefLoadingCollectionEntries.get( key );
if ( rtn == null ) {
LOG.tracev( "Collection [{0}] not located in load context", key );
}
else {
LOG.tracev( "Collection [{0}] located in load context", key );
}
return rtn;
}
/*package*/void cleanupCollectionXRefs(Set<CollectionKey> entryKeys) {
for ( CollectionKey entryKey : entryKeys ) {
xrefLoadingCollectionEntries.remove( entryKey );
}
}
// Entity load contexts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// * currently, not yet used...
/**
* Currently unused
*
* @param resultSet The result set
*
* @return The entity load context
*/
@SuppressWarnings( {"UnusedDeclaration"})
public EntityLoadContext getEntityLoadContext(ResultSet resultSet) {
EntityLoadContext context = null;
if ( entityLoadContexts == null ) {
entityLoadContexts = new IdentityHashMap<ResultSet, EntityLoadContext>( 8 );
}
else {
context = entityLoadContexts.get( resultSet );
}
if ( context == null ) {
context = new EntityLoadContext( this, resultSet );
entityLoadContexts.put( resultSet, context );
}
return context;
}
}

View File

@ -1,58 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.loading.internal;
import java.io.Serializable;
import java.sql.ResultSet;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.pretty.MessageHelper;
/**
* Represents a collection currently being loaded.
*
* @author Steve Ebersole
*/
public class LoadingCollectionEntry {
private final ResultSet resultSet;
private final CollectionPersister persister;
private final Serializable key;
private final PersistentCollection collection;
LoadingCollectionEntry(
ResultSet resultSet,
CollectionPersister persister,
Serializable key,
PersistentCollection collection) {
this.resultSet = resultSet;
this.persister = persister;
this.key = key;
this.collection = collection;
}
public ResultSet getResultSet() {
return resultSet;
}
public CollectionPersister getPersister() {
return persister;
}
public Serializable getKey() {
return key;
}
public PersistentCollection getCollection() {
return collection;
}
@Override
public String toString() {
return getClass().getName() + "<rs=" + resultSet + ", coll=" + MessageHelper.collectionInfoString( persister.getRole(), key ) + ">@" + Integer.toHexString( hashCode() );
}
}

View File

@ -1,11 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
/**
* Internal classes used to track loading of data, potentially across multiple ResultSets
*/
package org.hibernate.engine.loading.internal;

View File

@ -1,454 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.engine.query.spi;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Filter;
import org.hibernate.HibernateException;
import org.hibernate.QueryException;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.event.spi.EventSource;
import org.hibernate.hql.internal.QuerySplitter;
import org.hibernate.hql.spi.FilterTranslator;
import org.hibernate.hql.spi.NamedParameterInformation;
import org.hibernate.hql.spi.ParameterTranslations;
import org.hibernate.hql.spi.PositionalParameterInformation;
import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.internal.util.collections.IdentitySet;
import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.query.internal.ParameterMetadataImpl;
import org.hibernate.query.spi.ScrollableResultsImplementor;
import org.hibernate.type.Type;
/**
* Defines a query execution plan for an HQL query (or filter).
*
* @author Steve Ebersole
*/
public class HQLQueryPlan implements Serializable {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( HQLQueryPlan.class );
// TODO : keep separate notions of QT[] here for shallow/non-shallow queries...
private final String sourceQuery;
private final QueryTranslator[] translators;
private final ParameterMetadataImpl parameterMetadata;
private final ReturnMetadata returnMetadata;
private final Set querySpaces;
private final Set<String> enabledFilterNames;
private final boolean shallow;
/**
* Constructs a HQLQueryPlan
*
* @param hql The HQL query
* @param shallow Whether the execution is to be shallow or not
* @param enabledFilters The enabled filters (we only keep the names)
* @param factory The factory
*/
public HQLQueryPlan(String hql, boolean shallow, Map<String,Filter> enabledFilters,
SessionFactoryImplementor factory) {
this( hql, null, shallow, enabledFilters, factory, null );
}
public HQLQueryPlan(String hql, boolean shallow, Map<String,Filter> enabledFilters,
SessionFactoryImplementor factory, EntityGraphQueryHint entityGraphQueryHint) {
this( hql, null, shallow, enabledFilters, factory, entityGraphQueryHint );
}
@SuppressWarnings("unchecked")
protected HQLQueryPlan(
String hql,
String collectionRole,
boolean shallow,
Map<String,Filter> enabledFilters,
SessionFactoryImplementor factory,
EntityGraphQueryHint entityGraphQueryHint) {
this.sourceQuery = hql;
this.shallow = shallow;
if ( enabledFilters.isEmpty() ) {
this.enabledFilterNames = Collections.emptySet();
}
else {
this.enabledFilterNames = Collections.unmodifiableSet( new HashSet<>( enabledFilters.keySet() ) );
}
final String[] concreteQueryStrings = QuerySplitter.concreteQueries( hql, factory );
final int length = concreteQueryStrings.length;
this.translators = new QueryTranslator[length];
final Set<Serializable> combinedQuerySpaces = new HashSet<>();
final Map querySubstitutions = factory.getSessionFactoryOptions().getQuerySubstitutions();
final QueryTranslatorFactory queryTranslatorFactory = factory.getServiceRegistry().getService( QueryTranslatorFactory.class );
for ( int i=0; i<length; i++ ) {
if ( collectionRole == null ) {
translators[i] = queryTranslatorFactory
.createQueryTranslator( hql, concreteQueryStrings[i], enabledFilters, factory, entityGraphQueryHint );
translators[i].compile( querySubstitutions, shallow );
}
else {
translators[i] = queryTranslatorFactory
.createFilterTranslator( hql, concreteQueryStrings[i], enabledFilters, factory );
( (FilterTranslator) translators[i] ).compile( collectionRole, querySubstitutions, shallow );
}
combinedQuerySpaces.addAll( translators[i].getQuerySpaces() );
}
this.querySpaces = combinedQuerySpaces;
if ( length == 0 ) {
parameterMetadata = new ParameterMetadataImpl( null, null );
returnMetadata = null;
}
else {
this.parameterMetadata = buildParameterMetadata( translators[0].getParameterTranslations(), hql );
if ( translators[0].isManipulationStatement() ) {
returnMetadata = null;
}
else {
final Type[] types = ( length > 1 ) ? new Type[translators[0].getReturnTypes().length] : translators[0].getReturnTypes();
returnMetadata = new ReturnMetadata( translators[0].getReturnAliases(), types );
}
}
}
public String getSourceQuery() {
return sourceQuery;
}
public Set getQuerySpaces() {
return querySpaces;
}
public ParameterMetadataImpl getParameterMetadata() {
return parameterMetadata;
}
public ReturnMetadata getReturnMetadata() {
return returnMetadata;
}
public Set getEnabledFilterNames() {
return enabledFilterNames;
}
/**
* This method should only be called for debugging purposes as it regenerates a new array every time.
*/
public String[] getSqlStrings() {
List<String> sqlStrings = new ArrayList<>();
for ( QueryTranslator translator : translators ) {
sqlStrings.addAll( translator.collectSqlStrings() );
}
return ArrayHelper.toStringArray( sqlStrings );
}
public Set getUtilizedFilterNames() {
// TODO : add this info to the translator and aggregate it here...
return null;
}
public boolean isShallow() {
return shallow;
}
/**
* Coordinates the efforts to perform a list across all the included query translators.
*
* @param queryParameters The query parameters
* @param session The session
*
* @return The query result list
*
* @throws HibernateException Indicates a problem performing the query
*/
@SuppressWarnings("unchecked")
public List performList(
QueryParameters queryParameters,
SharedSessionContractImplementor session) throws HibernateException {
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Find: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
final RowSelection rowSelection = queryParameters.getRowSelection();
final boolean hasLimit = rowSelection != null
&& rowSelection.definesLimits();
final boolean needsLimit = hasLimit && translators.length > 1;
final QueryParameters queryParametersToUse;
if ( needsLimit ) {
LOG.needsLimit();
final RowSelection selection = new RowSelection();
selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() );
selection.setTimeout( queryParameters.getRowSelection().getTimeout() );
queryParametersToUse = queryParameters.createCopyUsing( selection );
}
else {
queryParametersToUse = queryParameters;
}
//fast path to avoid unnecessary allocation and copying
if ( translators.length == 1 ) {
return translators[0].list( session, queryParametersToUse );
}
final int guessedResultSize = guessResultSize( rowSelection );
final List combinedResults = new ArrayList( guessedResultSize );
final IdentitySet distinction;
if ( needsLimit ) {
distinction = new IdentitySet( guessedResultSize );
}
else {
distinction = null;
}
int includedCount = -1;
translator_loop:
for ( QueryTranslator translator : translators ) {
final List tmp = translator.list( session, queryParametersToUse );
if ( needsLimit ) {
// NOTE : firstRow is zero-based
final int first = queryParameters.getRowSelection().getFirstRow() == null
? 0
: queryParameters.getRowSelection().getFirstRow();
final int max = queryParameters.getRowSelection().getMaxRows() == null
? -1
: queryParameters.getRowSelection().getMaxRows();
for ( final Object result : tmp ) {
if ( !distinction.add( result ) ) {
continue;
}
includedCount++;
if ( includedCount < first ) {
continue;
}
combinedResults.add( result );
if ( max >= 0 && includedCount > max ) {
// break the outer loop !!!
break translator_loop;
}
}
}
else {
combinedResults.addAll( tmp );
}
}
return combinedResults;
}
/**
* If we're able to guess a likely size of the results we can optimize allocation
* of our datastructures.
* Essentially if we detect the user is not using pagination, we attempt to use the FetchSize
* as a reasonable hint. If fetch size is not being set either, it is reasonable to expect
* that we're going to have a single hit. In such a case it would be tempting to return a constant
* of value one, but that's dangerous as it doesn't scale up appropriately for example
* with an ArrayList if the guess is wrong.
*
* @param rowSelection
* @return a reasonable size to use for allocation
*/
@SuppressWarnings("UnnecessaryUnboxing")
private int guessResultSize(RowSelection rowSelection) {
if ( rowSelection != null ) {
final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100;
if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) {
return Math.min( maxReasonableAllocation, rowSelection.getMaxRows().intValue() );
}
else if ( rowSelection.getFetchSize() != null && rowSelection.getFetchSize().intValue() > 0 ) {
return rowSelection.getFetchSize().intValue();
}
}
return 7;//magic number guessed as a reasonable default.
}
/**
* Coordinates the efforts to perform an iterate across all the included query translators.
*
* @param queryParameters The query parameters
* @param session The session
*
* @return The query result iterator
*
* @throws HibernateException Indicates a problem performing the query
*/
@SuppressWarnings("unchecked")
public Iterator performIterate(
QueryParameters queryParameters,
EventSource session) throws HibernateException {
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
if ( translators.length == 0 ) {
return Collections.emptyIterator();
}
final boolean many = translators.length > 1;
Iterator[] results = null;
if ( many ) {
results = new Iterator[translators.length];
}
Iterator result = null;
for ( int i = 0; i < translators.length; i++ ) {
result = translators[i].iterate( queryParameters, session );
if ( many ) {
results[i] = result;
}
}
return many ? new JoinedIterator( results ) : result;
}
/**
* Coordinates the efforts to perform a scroll across all the included query translators.
*
* @param queryParameters The query parameters
* @param session The session
*
* @return The query result iterator
*
* @throws HibernateException Indicates a problem performing the query
*/
public ScrollableResultsImplementor performScroll(
QueryParameters queryParameters,
SharedSessionContractImplementor session) throws HibernateException {
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
if ( translators.length != 1 ) {
throw new QueryException( "implicit polymorphism not supported for scroll() queries" );
}
if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) {
throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" );
}
return translators[0].scroll( queryParameters, session );
}
/**
* Coordinates the efforts to perform an execution across all the included query translators.
*
* @param queryParameters The query parameters
* @param session The session
*
* @return The aggregated "affected row" count
*
* @throws HibernateException Indicates a problem performing the execution
*/
public int performExecuteUpdate(QueryParameters queryParameters, SharedSessionContractImplementor session)
throws HibernateException {
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Execute update: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
if ( translators.length != 1 ) {
LOG.splitQueries( getSourceQuery(), translators.length );
}
int result = 0;
for ( QueryTranslator translator : translators ) {
result += translator.executeUpdate( queryParameters, session );
}
return result;
}
private ParameterMetadataImpl buildParameterMetadata(ParameterTranslations parameterTranslations, String hql) {
final Map<Integer,OrdinalParameterDescriptor> ordinalParamDescriptors;
if ( parameterTranslations.getPositionalParameterInformationMap().isEmpty() ) {
ordinalParamDescriptors = Collections.emptyMap();
}
else {
final Map<Integer,OrdinalParameterDescriptor> temp = new HashMap<>();
for ( Map.Entry<Integer, PositionalParameterInformation> entry :
parameterTranslations.getPositionalParameterInformationMap().entrySet() ) {
final int position = entry.getKey();
temp.put(
position,
new OrdinalParameterDescriptor(
position,
position - 1,
entry.getValue().getExpectedType(),
entry.getValue().getSourceLocations()
)
);
}
ordinalParamDescriptors = Collections.unmodifiableMap( temp );
}
final Map<String, NamedParameterDescriptor> namedParamDescriptorMap;
if ( parameterTranslations.getNamedParameterInformationMap().isEmpty() ) {
namedParamDescriptorMap = Collections.emptyMap();
}
else {
final Map<String, NamedParameterDescriptor> tmp = new HashMap<>();
for ( Map.Entry<String, NamedParameterInformation> namedEntry :
parameterTranslations.getNamedParameterInformationMap().entrySet() ) {
final String name = namedEntry.getKey();
tmp.put(
name,
new NamedParameterDescriptor(
name,
parameterTranslations.getNamedParameterInformation( name ).getExpectedType(),
namedEntry.getValue().getSourceLocations()
)
);
}
namedParamDescriptorMap = Collections.unmodifiableMap( tmp );
}
return new ParameterMetadataImpl( ordinalParamDescriptors, namedParamDescriptorMap );
}
/**
* Access to the underlying translators associated with this query
*
* @return The translators
*/
public QueryTranslator[] getTranslators() {
final QueryTranslator[] copy = new QueryTranslator[translators.length];
System.arraycopy( translators, 0, copy, 0, copy.length );
return copy;
}
public Class getDynamicInstantiationResultType() {
return translators[0].getDynamicInstantiationResultType();
}
public boolean isSelect() {
return !translators[0].isManipulationStatement();
}
public boolean isUpdate() {
return translators[0].isUpdateStatement();
}
}

View File

@ -12,6 +12,7 @@ import java.sql.SQLException;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.action.internal.BulkOperationCleanupAction; import org.hibernate.action.internal.BulkOperationCleanupAction;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.event.spi.EventSource; import org.hibernate.event.spi.EventSource;

View File

@ -23,12 +23,12 @@ import org.hibernate.type.Type;
*/ */
public final class CollectionKey implements Serializable { public final class CollectionKey implements Serializable {
private final String role; private final String role;
private final Serializable key; private final Object key;
private final Type keyType; private final Type keyType;
private final SessionFactoryImplementor factory; private final SessionFactoryImplementor factory;
private final int hashCode; private final int hashCode;
public CollectionKey(CollectionPersister persister, Serializable key) { public CollectionKey(CollectionPersister persister, Object key) {
this( this(
persister.getRole(), persister.getRole(),
key, key,
@ -39,16 +39,16 @@ public final class CollectionKey implements Serializable {
/** /**
* The EntityMode parameter is now ignored. Use the other constructor. * The EntityMode parameter is now ignored. Use the other constructor.
* @deprecated Use {@link #CollectionKey(CollectionPersister, Serializable)} * @deprecated Use {@link #CollectionKey(CollectionPersister, Object)}
*/ */
@Deprecated @Deprecated
public CollectionKey(CollectionPersister persister, Serializable key, EntityMode em) { public CollectionKey(CollectionPersister persister, Object key, EntityMode em) {
this( persister.getRole(), key, persister.getKeyType(), persister.getFactory() ); this( persister.getRole(), key, persister.getKeyType(), persister.getFactory() );
} }
private CollectionKey( private CollectionKey(
String role, String role,
Serializable key, Object key,
Type keyType, Type keyType,
SessionFactoryImplementor factory) { SessionFactoryImplementor factory) {
this.role = role; this.role = role;
@ -70,7 +70,7 @@ public final class CollectionKey implements Serializable {
return role; return role;
} }
public Serializable getKey() { public Object getKey() {
return key; return key;
} }

View File

@ -12,6 +12,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier;
import javax.persistence.EntityGraph; import javax.persistence.EntityGraph;
@ -20,6 +21,7 @@ import org.hibernate.UnknownProfileException;
import org.hibernate.graph.GraphSemantic; import org.hibernate.graph.GraphSemantic;
import org.hibernate.graph.spi.RootGraphImplementor; import org.hibernate.graph.spi.RootGraphImplementor;
import org.hibernate.internal.FilterImpl; import org.hibernate.internal.FilterImpl;
import org.hibernate.loader.spi.InternalFetchProfile;
import org.hibernate.type.Type; import org.hibernate.type.Type;
/** /**
@ -42,7 +44,7 @@ public class LoadQueryInfluencers implements Serializable {
private final SessionFactoryImplementor sessionFactory; private final SessionFactoryImplementor sessionFactory;
private String internalFetchProfile; private InternalFetchProfile enabledInternalFetchProfile;
//Lazily initialized! //Lazily initialized!
private HashSet<String> enabledFetchProfileNames; private HashSet<String> enabledFetchProfileNames;
@ -67,17 +69,57 @@ public class LoadQueryInfluencers implements Serializable {
// internal fetch profile support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // internal fetch profile support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public String getInternalFetchProfile() { public void withInternalFetchProfile(InternalFetchProfile profile, InternalFetchProfileAction action) {
return internalFetchProfile; final InternalFetchProfile previous = this.enabledInternalFetchProfile;
this.enabledInternalFetchProfile = profile;
action.performAction();
this.enabledInternalFetchProfile = previous;
} }
public void setInternalFetchProfile(String internalFetchProfile) { public <T> T fromInternalFetchProfile(InternalFetchProfile profile, Supplier<T> supplier) {
final InternalFetchProfile previous = this.enabledInternalFetchProfile;
this.enabledInternalFetchProfile = profile;
try {
return supplier.get();
}
finally {
this.enabledInternalFetchProfile = previous;
}
}
@FunctionalInterface
public interface InternalFetchProfileAction {
void performAction();
}
public InternalFetchProfile getEnabledInternalFetchProfile() {
return enabledInternalFetchProfile;
}
public void setEnabledInternalFetchProfile(InternalFetchProfile enabledInternalFetchProfile) {
if ( sessionFactory == null ) { if ( sessionFactory == null ) {
// thats the signal that this is the immutable, context-less // thats the signal that this is the immutable, context-less
// variety // variety
throw new IllegalStateException( "Cannot modify context-less LoadQueryInfluencers" ); throw new IllegalStateException( "Cannot modify context-less LoadQueryInfluencers" );
} }
this.internalFetchProfile = internalFetchProfile;
this.enabledInternalFetchProfile = enabledInternalFetchProfile;
}
/**
* @deprecated Use {@link #getEnabledInternalFetchProfile} instead
*/
@Deprecated
public String getInternalFetchProfile() {
return getEnabledInternalFetchProfile().getLegacyName();
}
/**
* @deprecated Use {@link #setEnabledInternalFetchProfile} instead
*/
@Deprecated
public void setInternalFetchProfile(String internalFetchProfile) {
setEnabledInternalFetchProfile( InternalFetchProfile.fromLegacyName( internalFetchProfile ) );
} }

View File

@ -399,14 +399,17 @@ public interface PersistenceContext {
* add an (initialized) collection that was created by another session and passed * add an (initialized) collection that was created by another session and passed
* into update() (ie. one with a snapshot and existing state on the database) * into update() (ie. one with a snapshot and existing state on the database)
*/ */
void addInitializedDetachedCollection(CollectionPersister collectionPersister, void addInitializedDetachedCollection(
PersistentCollection collection) throws HibernateException; CollectionPersister collectionPersister,
PersistentCollection collection);
/** /**
* add a collection we just pulled out of the cache (does not need initializing) * add a collection we just pulled out of the cache (does not need initializing)
*/ */
CollectionEntry addInitializedCollection(CollectionPersister persister, CollectionEntry addInitializedCollection(
PersistentCollection collection, Serializable id) throws HibernateException; CollectionPersister persister,
PersistentCollection collection,
Object id);
/** /**
* Get the collection instance associated with the <tt>CollectionKey</tt> * Get the collection instance associated with the <tt>CollectionKey</tt>
@ -453,7 +456,11 @@ public interface PersistenceContext {
* Get the collection entry for a collection passed to filter, * Get the collection entry for a collection passed to filter,
* which might be a collection wrapper, an array, or an unwrapped * which might be a collection wrapper, an array, or an unwrapped
* collection. Return null if there is no entry. * collection. Return null if there is no entry.
*
* @deprecated Intended use was in handling Hibernate's legacy
* "collection filter via Query" feature which has been removed
*/ */
@Deprecated
CollectionEntry getCollectionEntryOrNull(Object collection); CollectionEntry getCollectionEntryOrNull(Object collection);
/** /**

View File

@ -7,23 +7,17 @@
package org.hibernate.engine.spi; package org.hibernate.engine.spi;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.StringTokenizer;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.LockOptions; import org.hibernate.LockOptions;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.ScrollMode; import org.hibernate.ScrollMode;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.FilterImpl;
import org.hibernate.internal.util.EntityPrinter; import org.hibernate.internal.util.EntityPrinter;
import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.query.spi.QueryOptions;
import org.hibernate.query.spi.QueryParameterBindings; import org.hibernate.query.spi.QueryParameterBindings;
import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.ComponentType; import org.hibernate.type.ComponentType;
@ -226,13 +220,7 @@ public final class QueryParameters {
public QueryParameters( public QueryParameters(
QueryParameterBindings queryParameterBindings, QueryParameterBindings queryParameterBindings,
LockOptions lockOptions, LockOptions lockOptions,
RowSelection selection, QueryOptions queryOptions,
final boolean isReadOnlyInitialized,
boolean readOnly,
boolean cacheable,
String cacheRegion,
String comment,
List<String> dbHints,
final Serializable[] collectionKeys, final Serializable[] collectionKeys,
final Object optionalObject, final Object optionalObject,
final String optionalEntityName, final String optionalEntityName,
@ -243,13 +231,18 @@ public final class QueryParameters {
null, null,
null, null,
lockOptions, lockOptions,
selection, new RowSelection(
isReadOnlyInitialized, queryOptions.getFirstRow(),
readOnly, queryOptions.getMaxRows(),
cacheable, queryOptions.getTimeout(),
cacheRegion, queryOptions.getFetchSize()
comment, ),
dbHints, queryOptions.isReadOnly() != null,
queryOptions.isReadOnly(),
queryOptions.isResultCachingEnabled(),
queryOptions.getResultCacheRegionName(),
queryOptions.getComment(),
queryOptions.getDatabaseHints(),
collectionKeys, collectionKeys,
optionalObject, optionalObject,
optionalEntityName, optionalEntityName,

View File

@ -17,6 +17,16 @@ public final class RowSelection {
private Integer timeout; private Integer timeout;
private Integer fetchSize; private Integer fetchSize;
public RowSelection() {
}
public RowSelection(Integer firstRow, Integer maxRows, Integer timeout, Integer fetchSize) {
this.firstRow = firstRow;
this.maxRows = maxRows;
this.timeout = timeout;
this.fetchSize = fetchSize;
}
public void setFirstRow(Integer firstRow) { public void setFirstRow(Integer firstRow) {
if ( firstRow != null && firstRow < 0 ) { if ( firstRow != null && firstRow < 0 ) {
throw new IllegalArgumentException( "first-row value cannot be negative : " + firstRow ); throw new IllegalArgumentException( "first-row value cannot be negative : " + firstRow );

View File

@ -24,6 +24,7 @@ import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.PersistentAttributeInterceptable; import org.hibernate.engine.spi.PersistentAttributeInterceptable;
import org.hibernate.engine.spi.PersistentAttributeInterceptor; import org.hibernate.engine.spi.PersistentAttributeInterceptor;
import org.hibernate.loader.spi.InternalFetchProfile;
import org.hibernate.engine.spi.SelfDirtinessTracker; import org.hibernate.engine.spi.SelfDirtinessTracker;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
@ -297,15 +298,15 @@ public class DefaultMergeEventListener extends AbstractSaveEventListener impleme
} }
} }
String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile(); // we must clone embedded composite identifiers or we will get back the same instance that we pass in
source.getLoadQueryInfluencers().setInternalFetchProfile( "merge" );
//we must clone embedded composite identifiers, or
//we will get back the same instance that we pass in
final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType().deepCopy( id, source.getFactory() ); final Serializable clonedIdentifier = (Serializable) persister.getIdentifierType().deepCopy( id, source.getFactory() );
final Object result = source.get( entityName, clonedIdentifier );
source.getLoadQueryInfluencers().setInternalFetchProfile( previousFetchProfile ); // apply the special MERGE fetch profile and perform the resolution (Session#get)
final Object result = source.getLoadQueryInfluencers().fromInternalFetchProfile(
InternalFetchProfile.MERGE,
() -> source.get( entityName, clonedIdentifier )
);
if ( result == null ) { if ( result == null ) {
//TODO: we should throw an exception if we really *know* for sure //TODO: we should throw an exception if we really *know* for sure

View File

@ -31,6 +31,7 @@ import org.hibernate.event.spi.RefreshEvent;
import org.hibernate.event.spi.RefreshEventListener; import org.hibernate.event.spi.RefreshEventListener;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.loader.spi.InternalFetchProfile;
import org.hibernate.metamodel.spi.MetamodelImplementor; import org.hibernate.metamodel.spi.MetamodelImplementor;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
@ -171,9 +172,22 @@ public class DefaultRefreshEventListener implements RefreshEventListener {
evictCachedCollections( persister, id, source ); evictCachedCollections( persister, id, source );
String previousFetchProfile = source.getLoadQueryInfluencers().getInternalFetchProfile(); final Object result = source.getLoadQueryInfluencers().fromInternalFetchProfile(
source.getLoadQueryInfluencers().setInternalFetchProfile( "refresh" ); InternalFetchProfile.REFRESH,
() -> doRefresh( event, source, object, e, persister, id )
);
UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
}
private Object doRefresh(
RefreshEvent event,
EventSource source,
Object object,
EntityEntry e,
EntityPersister persister,
Serializable id) {
// Handle the requested lock-mode (if one) in relation to the entry's (if one) current lock-mode // Handle the requested lock-mode (if one) in relation to the entry's (if one) current lock-mode
@ -230,10 +244,7 @@ public class DefaultRefreshEventListener implements RefreshEventListener {
source.setReadOnly( result, ( e == null ? source.isDefaultReadOnly() : e.isReadOnly() ) ); source.setReadOnly( result, ( e == null ? source.isDefaultReadOnly() : e.isReadOnly() ) );
} }
} }
source.getLoadQueryInfluencers().setInternalFetchProfile( previousFetchProfile ); return result;
UnresolvableObjectException.throwIfNull( result, id, persister.getEntityName() );
} }
private void evictCachedCollections(EntityPersister persister, Serializable id, EventSource source) { private void evictCachedCollections(EntityPersister persister, Serializable id, EventSource source) {

View File

@ -30,8 +30,6 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.jdbc.dialect.spi.DialectResolver; import org.hibernate.engine.jdbc.dialect.spi.DialectResolver;
import org.hibernate.engine.jndi.JndiException; import org.hibernate.engine.jndi.JndiException;
import org.hibernate.engine.jndi.JndiNameException; import org.hibernate.engine.jndi.JndiNameException;
import org.hibernate.engine.loading.internal.CollectionLoadContext;
import org.hibernate.engine.loading.internal.EntityLoadContext;
import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.IntegralDataTypeHolder; import org.hibernate.id.IntegralDataTypeHolder;
@ -307,13 +305,13 @@ public interface CoreMessageLogger extends BasicLogger {
+ " to unsafe use of the session): %s", id = 99) + " to unsafe use of the session): %s", id = 99)
void failed(Throwable throwable); void failed(Throwable throwable);
@LogMessage(level = WARN) // @LogMessage(level = WARN)
@Message(value = "Fail-safe cleanup (collections) : %s", id = 100) // @Message(value = "Fail-safe cleanup (collections) : %s", id = 100)
void failSafeCollectionsCleanup(CollectionLoadContext collectionLoadContext); // void failSafeCollectionsCleanup(CollectionLoadContext collectionLoadContext);
//
@LogMessage(level = WARN) // @LogMessage(level = WARN)
@Message(value = "Fail-safe cleanup (entities) : %s", id = 101) // @Message(value = "Fail-safe cleanup (entities) : %s", id = 101)
void failSafeEntitiesCleanup(EntityLoadContext entityLoadContext); // void failSafeEntitiesCleanup(EntityLoadContext entityLoadContext);
@LogMessage(level = INFO) @LogMessage(level = INFO)
@Message(value = "Fetching database metadata", id = 102) @Message(value = "Fetching database metadata", id = 102)

View File

@ -1,730 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.NaturalIdentifier;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.query.internal.AbstractProducedQuery;
import org.hibernate.sql.JoinType;
import org.hibernate.transform.ResultTransformer;
/**
* Implementation of the <tt>Criteria</tt> interface
* @author Gavin King
*/
public class CriteriaImpl implements Criteria, Serializable {
private final String entityOrClassName;
private transient SharedSessionContractImplementor session;
private final String rootAlias;
private List<CriterionEntry> criterionEntries = new ArrayList<>();
private List<OrderEntry> orderEntries = new ArrayList<>();
private Projection projection;
private Criteria projectionCriteria;
private List<Subcriteria> subcriteriaList = new ArrayList<>();
private Map<String, FetchMode> fetchModes = new HashMap<>();
private Map<String, LockMode> lockModes = new HashMap<>();
private Integer maxResults;
private Integer firstResult;
private Integer timeout;
private Integer fetchSize;
private boolean cacheable;
private String cacheRegion;
private String comment;
private final List<String> queryHints = new ArrayList<String>();
private FlushMode flushMode;
private CacheMode cacheMode;
private FlushMode sessionFlushMode;
private CacheMode sessionCacheMode;
private Boolean readOnly;
private ResultTransformer resultTransformer = Criteria.ROOT_ENTITY;
// Constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public CriteriaImpl(String entityOrClassName, SharedSessionContractImplementor session) {
this(entityOrClassName, ROOT_ALIAS, session);
}
public CriteriaImpl(String entityOrClassName, String alias, SharedSessionContractImplementor session) {
this.session = session;
this.entityOrClassName = entityOrClassName;
this.cacheable = false;
this.rootAlias = alias;
}
@Override
public String toString() {
return "CriteriaImpl(" +
entityOrClassName + ":" +
(rootAlias==null ? "" : rootAlias) +
subcriteriaList.toString() +
criterionEntries.toString() +
( projection==null ? "" : projection.toString() ) +
')';
}
// State ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public SharedSessionContractImplementor getSession() {
return session;
}
public void setSession(SharedSessionContractImplementor session) {
this.session = session;
}
public String getEntityOrClassName() {
return entityOrClassName;
}
public Map<String, LockMode> getLockModes() {
return lockModes;
}
public Criteria getProjectionCriteria() {
return projectionCriteria;
}
public Iterator<Subcriteria> iterateSubcriteria() {
return subcriteriaList.iterator();
}
public Iterator<CriterionEntry> iterateExpressionEntries() {
return criterionEntries.iterator();
}
public Iterator<OrderEntry> iterateOrderings() {
return orderEntries.iterator();
}
public Criteria add(Criteria criteriaInst, Criterion expression) {
criterionEntries.add( new CriterionEntry(expression, criteriaInst) );
return this;
}
// Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public String getAlias() {
return rootAlias;
}
public Projection getProjection() {
return projection;
}
@Override
public Criteria setProjection(Projection projection) {
this.projection = projection;
this.projectionCriteria = this;
setResultTransformer( PROJECTION );
return this;
}
@Override
public Criteria add(Criterion expression) {
add( this, expression );
return this;
}
@Override
public Criteria addOrder(Order ordering) {
orderEntries.add( new OrderEntry( ordering, this ) );
return this;
}
public FetchMode getFetchMode(String path) {
return fetchModes.get(path);
}
@Override
public Criteria setFetchMode(String associationPath, FetchMode mode) {
String rootAliasPathPrefix = rootAlias + ".";
if (rootAlias != null && !associationPath.startsWith(rootAliasPathPrefix)) {
associationPath = rootAliasPathPrefix + associationPath;
}
fetchModes.put( associationPath, mode );
return this;
}
@Override
public Criteria setLockMode(LockMode lockMode) {
return setLockMode( getAlias(), lockMode );
}
@Override
public Criteria setLockMode(String alias, LockMode lockMode) {
lockModes.put( alias, lockMode );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias) {
return createAlias( associationPath, alias, JoinType.INNER_JOIN );
}
@Override
public Criteria createAlias(String associationPath, String alias, JoinType joinType) {
new Subcriteria( this, associationPath, alias, joinType );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException {
return createAlias( associationPath, alias, JoinType.parse( joinType ) );
}
@Override
public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) {
new Subcriteria( this, associationPath, alias, joinType, withClause );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause)
throws HibernateException {
return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause );
}
@Override
public Criteria createCriteria(String associationPath) {
return createCriteria( associationPath, JoinType.INNER_JOIN );
}
@Override
public Criteria createCriteria(String associationPath, JoinType joinType) {
return new Subcriteria( this, associationPath, joinType );
}
@Override
public Criteria createCriteria(String associationPath, int joinType) throws HibernateException {
return createCriteria(associationPath, JoinType.parse( joinType ));
}
@Override
public Criteria createCriteria(String associationPath, String alias) {
return createCriteria( associationPath, alias, JoinType.INNER_JOIN );
}
@Override
public Criteria createCriteria(String associationPath, String alias, JoinType joinType) {
return new Subcriteria( this, associationPath, alias, joinType );
}
@Override
public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException {
return createCriteria( associationPath, alias, JoinType.parse( joinType ) );
}
@Override
public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) {
return new Subcriteria( this, associationPath, alias, joinType, withClause );
}
@Override
public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause)
throws HibernateException {
return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause );
}
public ResultTransformer getResultTransformer() {
return resultTransformer;
}
@Override
public Criteria setResultTransformer(ResultTransformer tupleMapper) {
this.resultTransformer = tupleMapper;
return this;
}
public Integer getMaxResults() {
return maxResults;
}
@Override
public Criteria setMaxResults(int maxResults) {
this.maxResults = maxResults;
return this;
}
public Integer getFirstResult() {
return firstResult;
}
@Override
public Criteria setFirstResult(int firstResult) {
this.firstResult = firstResult;
return this;
}
public Integer getFetchSize() {
return fetchSize;
}
@Override
public Criteria setFetchSize(int fetchSize) {
this.fetchSize = fetchSize;
return this;
}
public Integer getTimeout() {
return timeout;
}
@Override
public Criteria setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
@Override
public boolean isReadOnlyInitialized() {
return readOnly != null;
}
@Override
public boolean isReadOnly() {
if ( ! isReadOnlyInitialized() && getSession() == null ) {
throw new IllegalStateException(
"cannot determine readOnly/modifiable setting when it is not initialized and is not initialized and getSession() == null"
);
}
return ( isReadOnlyInitialized() ?
readOnly :
getSession().getPersistenceContextInternal().isDefaultReadOnly()
);
}
@Override
public Criteria setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
return this;
}
public boolean getCacheable() {
return this.cacheable;
}
@Override
public Criteria setCacheable(boolean cacheable) {
this.cacheable = cacheable;
return this;
}
public String getCacheRegion() {
return this.cacheRegion;
}
@Override
public Criteria setCacheRegion(String cacheRegion) {
this.cacheRegion = cacheRegion.trim();
return this;
}
public String getComment() {
return comment;
}
@Override
public Criteria setComment(String comment) {
this.comment = comment;
return this;
}
public List<String> getQueryHints() {
return queryHints;
}
@Override
public Criteria addQueryHint(String queryHint) {
queryHints.add( queryHint );
return this;
}
@Override
public Criteria setFlushMode(FlushMode flushMode) {
this.flushMode = flushMode;
return this;
}
@Override
public Criteria setCacheMode(CacheMode cacheMode) {
this.cacheMode = cacheMode;
return this;
}
@Override
public List list() throws HibernateException {
before();
try {
return session.list( this );
}
finally {
after();
}
}
@Override
public ScrollableResults scroll() {
return scroll( session.getFactory().getDialect().defaultScrollMode() );
}
@Override
public ScrollableResults scroll(ScrollMode scrollMode) {
before();
try {
return session.scroll(this, scrollMode);
}
finally {
after();
}
}
@Override
public Object uniqueResult() throws HibernateException {
return AbstractProducedQuery.uniqueElement( list() );
}
protected void before() {
if ( flushMode != null ) {
sessionFlushMode = getSession().getHibernateFlushMode();
getSession().setHibernateFlushMode( flushMode );
}
if ( cacheMode != null ) {
sessionCacheMode = getSession().getCacheMode();
getSession().setCacheMode( cacheMode );
}
}
protected void after() {
if ( sessionFlushMode != null ) {
getSession().setHibernateFlushMode( sessionFlushMode );
sessionFlushMode = null;
}
if ( sessionCacheMode != null ) {
getSession().setCacheMode( sessionCacheMode );
sessionCacheMode = null;
}
}
public boolean isLookupByNaturalKey() {
if ( projection != null ) {
return false;
}
if ( subcriteriaList.size() > 0 ) {
return false;
}
if ( criterionEntries.size() != 1 ) {
return false;
}
CriterionEntry ce = criterionEntries.get(0);
return ce.getCriterion() instanceof NaturalIdentifier;
}
// Inner classes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public final class Subcriteria implements Criteria, Serializable {
private String alias;
private String path;
private Criteria parent;
private LockMode lockMode;
private JoinType joinType = JoinType.INNER_JOIN;
private Criterion withClause;
private boolean hasRestriction;
// Constructors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private Subcriteria(Criteria parent, String path, String alias, JoinType joinType, Criterion withClause) {
this.alias = alias;
this.path = path;
this.parent = parent;
this.joinType = joinType;
this.withClause = withClause;
this.hasRestriction = withClause != null;
CriteriaImpl.this.subcriteriaList.add( this );
}
private Subcriteria(Criteria parent, String path, String alias, JoinType joinType) {
this( parent, path, alias, joinType, null );
}
private Subcriteria(Criteria parent, String path, JoinType joinType) {
this( parent, path, null, joinType );
}
@Override
public String toString() {
return "Subcriteria("
+ path + ":"
+ (alias==null ? "" : alias)
+ ')';
}
// State ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getPath() {
return path;
}
public Criteria getParent() {
return parent;
}
public LockMode getLockMode() {
return lockMode;
}
@Override
public Criteria setLockMode(LockMode lockMode) {
this.lockMode = lockMode;
return this;
}
public JoinType getJoinType() {
return joinType;
}
public Criterion getWithClause() {
return this.withClause;
}
public boolean hasRestriction() {
return hasRestriction;
}
// Criteria impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
public Criteria add(Criterion expression) {
hasRestriction = true;
CriteriaImpl.this.add(this, expression);
return this;
}
@Override
public Criteria addOrder(Order order) {
CriteriaImpl.this.orderEntries.add( new OrderEntry(order, this) );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias) {
return createAlias( associationPath, alias, JoinType.INNER_JOIN );
}
@Override
public Criteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException {
new Subcriteria( this, associationPath, alias, joinType );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias, int joinType) throws HibernateException {
return createAlias( associationPath, alias, JoinType.parse( joinType ) );
}
@Override
public Criteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException {
new Subcriteria( this, associationPath, alias, joinType, withClause );
return this;
}
@Override
public Criteria createAlias(String associationPath, String alias, int joinType, Criterion withClause)
throws HibernateException {
return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause );
}
@Override
public Criteria createCriteria(String associationPath) {
return createCriteria( associationPath, JoinType.INNER_JOIN );
}
@Override
public Criteria createCriteria(String associationPath, JoinType joinType) throws HibernateException {
return new Subcriteria( Subcriteria.this, associationPath, joinType );
}
@Override
public Criteria createCriteria(String associationPath, int joinType) throws HibernateException {
return createCriteria( associationPath, JoinType.parse( joinType ) );
}
@Override
public Criteria createCriteria(String associationPath, String alias) {
return createCriteria( associationPath, alias, JoinType.INNER_JOIN );
}
@Override
public Criteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException {
return new Subcriteria( Subcriteria.this, associationPath, alias, joinType );
}
@Override
public Criteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException {
return createCriteria( associationPath, alias, JoinType.parse( joinType ) );
}
@Override
public Criteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException {
return new Subcriteria( this, associationPath, alias, joinType, withClause );
}
@Override
public Criteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause)
throws HibernateException {
return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause );
}
@Override
public boolean isReadOnly() {
return CriteriaImpl.this.isReadOnly();
}
@Override
public boolean isReadOnlyInitialized() {
return CriteriaImpl.this.isReadOnlyInitialized();
}
@Override
public Criteria setReadOnly(boolean readOnly) {
CriteriaImpl.this.setReadOnly( readOnly );
return this;
}
@Override
public Criteria setCacheable(boolean cacheable) {
CriteriaImpl.this.setCacheable(cacheable);
return this;
}
@Override
public Criteria setCacheRegion(String cacheRegion) {
CriteriaImpl.this.setCacheRegion(cacheRegion);
return this;
}
@Override
public List list() throws HibernateException {
return CriteriaImpl.this.list();
}
@Override
public ScrollableResults scroll() throws HibernateException {
return CriteriaImpl.this.scroll();
}
@Override
public ScrollableResults scroll(ScrollMode scrollMode) throws HibernateException {
return CriteriaImpl.this.scroll(scrollMode);
}
@Override
public Object uniqueResult() throws HibernateException {
return CriteriaImpl.this.uniqueResult();
}
@Override
public Criteria setFetchMode(String associationPath, FetchMode mode) {
CriteriaImpl.this.setFetchMode( StringHelper.qualify(path, associationPath), mode);
return this;
}
@Override
public Criteria setFlushMode(FlushMode flushMode) {
CriteriaImpl.this.setFlushMode(flushMode);
return this;
}
@Override
public Criteria setCacheMode(CacheMode cacheMode) {
CriteriaImpl.this.setCacheMode(cacheMode);
return this;
}
@Override
public Criteria setFirstResult(int firstResult) {
CriteriaImpl.this.setFirstResult(firstResult);
return this;
}
@Override
public Criteria setMaxResults(int maxResults) {
CriteriaImpl.this.setMaxResults(maxResults);
return this;
}
@Override
public Criteria setTimeout(int timeout) {
CriteriaImpl.this.setTimeout(timeout);
return this;
}
@Override
public Criteria setFetchSize(int fetchSize) {
CriteriaImpl.this.setFetchSize(fetchSize);
return this;
}
@Override
public Criteria setLockMode(String alias, LockMode lockMode) {
CriteriaImpl.this.setLockMode(alias, lockMode);
return this;
}
@Override
public Criteria setResultTransformer(ResultTransformer resultProcessor) {
CriteriaImpl.this.setResultTransformer(resultProcessor);
return this;
}
@Override
public Criteria setComment(String comment) {
CriteriaImpl.this.setComment(comment);
return this;
}
@Override
public Criteria addQueryHint(String queryHint) {
CriteriaImpl.this.addQueryHint( queryHint );
return this;
}
@Override
public Criteria setProjection(Projection projection) {
CriteriaImpl.this.projection = projection;
CriteriaImpl.this.projectionCriteria = this;
setResultTransformer(PROJECTION);
return this;
}
}
public static final class CriterionEntry implements Serializable {
private final Criterion criterion;
private final Criteria criteria;
private CriterionEntry(Criterion criterion, Criteria criteria) {
this.criteria = criteria;
this.criterion = criterion;
}
public Criterion getCriterion() {
return criterion;
}
public Criteria getCriteria() {
return criteria;
}
@Override
public String toString() {
return criterion.toString();
}
}
public static final class OrderEntry implements Serializable {
private final Order order;
private final Criteria criteria;
private OrderEntry(Order order, Criteria criteria) {
this.criteria = criteria;
this.order = order;
}
public Order getOrder() {
return order;
}
public Criteria getCriteria() {
return criteria;
}
@Override
public String toString() {
return order.toString();
}
}
}

View File

@ -74,7 +74,6 @@ import org.hibernate.engine.internal.StatefulPersistenceContext;
import org.hibernate.engine.jdbc.LobCreator; import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.jdbc.NonContextualLobCreator; import org.hibernate.engine.jdbc.NonContextualLobCreator;
import org.hibernate.engine.jdbc.spi.JdbcCoordinator; import org.hibernate.engine.jdbc.spi.JdbcCoordinator;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan; import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification; import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.spi.ActionQueue; import org.hibernate.engine.spi.ActionQueue;
@ -83,6 +82,7 @@ import org.hibernate.engine.spi.EntityEntry;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;

View File

@ -9,18 +9,14 @@ package org.hibernate.internal;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.transaction.SystemException; import javax.transaction.SystemException;
import org.hibernate.CacheMode; import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.EntityMode; import org.hibernate.EntityMode;
import org.hibernate.FlushMode; import org.hibernate.FlushMode;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.MappingException;
import org.hibernate.ScrollMode;
import org.hibernate.SessionException; import org.hibernate.SessionException;
import org.hibernate.StatelessSession; import org.hibernate.StatelessSession;
import org.hibernate.UnresolvableObjectException; import org.hibernate.UnresolvableObjectException;
@ -29,20 +25,18 @@ import org.hibernate.cache.spi.access.EntityDataAccess;
import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.internal.StatefulPersistenceContext; import org.hibernate.engine.internal.StatefulPersistenceContext;
import org.hibernate.engine.internal.Versioning; import org.hibernate.engine.internal.Versioning;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.hibernate.engine.query.spi.NativeSQLQueryPlan; import org.hibernate.engine.query.spi.NativeSQLQueryPlan;
import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification; import org.hibernate.engine.query.spi.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper; import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.id.IdentifierGeneratorHelper; import org.hibernate.id.IdentifierGeneratorHelper;
import org.hibernate.loader.criteria.CriteriaLoader;
import org.hibernate.loader.custom.CustomLoader; import org.hibernate.loader.custom.CustomLoader;
import org.hibernate.loader.custom.CustomQuery; import org.hibernate.loader.custom.CustomQuery;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.OuterJoinLoadable;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.query.spi.ScrollableResultsImplementor; import org.hibernate.query.spi.ScrollableResultsImplementor;
@ -64,6 +58,7 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen
@Override @Override
public void setInternalFetchProfile(String internalFetchProfile) { public void setInternalFetchProfile(String internalFetchProfile) {
} }
}; };
private final PersistenceContext temporaryPersistenceContext = new StatefulPersistenceContext( this ); private final PersistenceContext temporaryPersistenceContext = new StatefulPersistenceContext( this );
@ -328,23 +323,6 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen
return get( entityName, id ); return get( entityName, id );
} }
@Override
public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List listFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override @Override
public boolean isAutoCloseSessionEnabled() { public boolean isAutoCloseSessionEnabled() {
return getFactory().getSessionFactoryOptions().isAutoCloseSessionEnabled(); return getFactory().getSessionFactoryOptions().isAutoCloseSessionEnabled();
@ -534,94 +512,6 @@ public class StatelessSessionImpl extends AbstractSharedSessionContract implemen
} }
} }
@Override
public Criteria createCriteria(Class persistentClass, String alias) {
checkOpen();
return new CriteriaImpl( persistentClass.getName(), alias, this );
}
@Override
public Criteria createCriteria(String entityName, String alias) {
checkOpen();
return new CriteriaImpl( entityName, alias, this );
}
@Override
public Criteria createCriteria(Class persistentClass) {
checkOpen();
return new CriteriaImpl( persistentClass.getName(), this );
}
@Override
public Criteria createCriteria(String entityName) {
checkOpen();
return new CriteriaImpl( entityName, this );
}
@Override
public ScrollableResultsImplementor scroll(Criteria criteria, ScrollMode scrollMode) {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
checkOpen();
String entityName = criteriaImpl.getEntityOrClassName();
CriteriaLoader loader = new CriteriaLoader(
getOuterJoinLoadable( entityName ),
getFactory(),
criteriaImpl,
entityName,
getLoadQueryInfluencers()
);
return loader.scroll( this, scrollMode );
}
@Override
@SuppressWarnings({"unchecked"})
public List list(Criteria criteria) throws HibernateException {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
checkOpen();
String[] implementors = getFactory().getMetamodel().getImplementors( criteriaImpl.getEntityOrClassName() );
int size = implementors.length;
CriteriaLoader[] loaders = new CriteriaLoader[size];
for ( int i = 0; i < size; i++ ) {
loaders[i] = new CriteriaLoader(
getOuterJoinLoadable( implementors[i] ),
getFactory(),
criteriaImpl,
implementors[i],
getLoadQueryInfluencers()
);
}
List results = Collections.EMPTY_LIST;
boolean success = false;
try {
for ( int i = 0; i < size; i++ ) {
final List currentResults = loaders[i].list( this );
currentResults.addAll( results );
results = currentResults;
}
success = true;
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
private OuterJoinLoadable getOuterJoinLoadable(String entityName) throws MappingException {
EntityPersister persister = getFactory().getMetamodel().entityPersister( entityName );
if ( !( persister instanceof OuterJoinLoadable ) ) {
throw new MappingException( "class persister is not OuterJoinLoadable: " + entityName );
}
return (OuterJoinLoadable) persister;
}
@Override @Override
public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException { throws HibernateException {

View File

@ -0,0 +1,62 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.internal.util.streams;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* @author Steve Ebersole
*/
public class GenericArrayCollector<T> implements Collector<T, List<T>, T[]> {
public static <T> GenericArrayCollector<T> forType(Class<T> type) {
return new GenericArrayCollector<T>( type );
}
private final Class<T> collectedType;
public GenericArrayCollector(Class<T> collectedType) {
this.collectedType = collectedType;
}
@Override
public Supplier<List<T>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<T>, T> accumulator() {
return List::add;
}
@Override
public BinaryOperator<List<T>> combiner() {
return (ts, ts2) -> {
ts.addAll( ts2 );
return ts;
};
}
@Override
@SuppressWarnings("unchecked")
public Function<List<T>, T[]> finisher() {
return ts -> ts.toArray( (T[]) Array.newInstance( collectedType, ts.size() ) );
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of( Characteristics.CONCURRENT );
}
}

View File

@ -0,0 +1,57 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.internal.util.streams;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
/**
* A Java 8 Stream Collector for collecting Strings into a String[].
*
* @author Steve Ebersole
*/
public class StingArrayCollector implements Collector<String, List<String>, String[]> {
/**
* Singleton access
*/
public static final StingArrayCollector INSTANCE = new StingArrayCollector();
@Override
public Supplier<List<String>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<String>, String> accumulator() {
return List::add;
}
@Override
public BinaryOperator<List<String>> combiner() {
return (strings, strings2) -> {
strings.addAll( strings2 );
return strings;
};
}
@Override
public Function<List<String>, String[]> finisher() {
return strings -> strings.toArray( new String[strings.size()] );
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of( Characteristics.CONCURRENT );
}
}

View File

@ -0,0 +1,21 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.internal.util.streams;
/**
* @author Steve Ebersole
*/
public class StreamUtils {
public static StingArrayCollector toStringArray() {
return StingArrayCollector.INSTANCE;
}
public static <T> GenericArrayCollector<T> toArray(Class<T> collectedType) {
return new GenericArrayCollector<>( collectedType );
}
}

View File

@ -1,25 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa;
import javax.persistence.Query;
/**
* Marker interface for Hibernate generated JPA queries so that we can access the underlying Hibernate query objects.
*
* @author Gavin King
* @author Emmanuel Bernard
* @author Steve Ebersole
*/
public interface HibernateQuery extends Query {
/**
* Gives access to the underlying Hibernate query object..
*
* @return THe Hibernate query object.
*/
public org.hibernate.Query getHibernateQuery();
}

View File

@ -1,151 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.jpa.spi;
import java.util.List;
import javax.persistence.Tuple;
import javax.persistence.TupleElement;
import org.hibernate.query.criteria.internal.ValueHandlerFactory;
import org.hibernate.transform.BasicTransformerAdapter;
/**
* ResultTransformer adapter for handling Tuple results from Criteria queries
*
* @author Steve Ebersole
*/
public class CriteriaQueryTupleTransformer extends BasicTransformerAdapter {
private final List<ValueHandlerFactory.ValueHandler> valueHandlers;
private final List tupleElements;
public CriteriaQueryTupleTransformer(List<ValueHandlerFactory.ValueHandler> valueHandlers, List tupleElements) {
// todo : should these 2 sizes match *always*?
this.valueHandlers = valueHandlers;
this.tupleElements = tupleElements;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
final Object[] valueHandlerResult;
if ( valueHandlers == null ) {
valueHandlerResult = tuple;
}
else {
valueHandlerResult = new Object[tuple.length];
for ( int i = 0; i < tuple.length; i++ ) {
ValueHandlerFactory.ValueHandler valueHandler = valueHandlers.get( i );
valueHandlerResult[i] = valueHandler == null
? tuple[i]
: valueHandler.convert( tuple[i] );
}
}
return tupleElements == null
? valueHandlerResult.length == 1 ? valueHandlerResult[0] : valueHandlerResult
: new TupleImpl( tuple );
}
private class TupleImpl implements Tuple {
private final Object[] tuples;
private TupleImpl(Object[] tuples) {
if ( tuples.length != tupleElements.size() ) {
throw new IllegalArgumentException(
"Size mismatch between tuple result [" + tuples.length
+ "] and expected tuple elements [" + tupleElements.size() + "]"
);
}
this.tuples = tuples;
}
public <X> X get(TupleElement<X> tupleElement) {
int index = tupleElements.indexOf( tupleElement );
if ( index < 0 ) {
throw new IllegalArgumentException(
"Requested tuple element did not correspond to element in the result tuple"
);
}
// index should be "in range" by nature of size check in ctor
return (X) tuples[index];
}
public Object get(String alias) {
int index = -1;
if ( alias != null ) {
alias = alias.trim();
if ( alias.length() > 0 ) {
int i = 0;
for ( TupleElement selection : (List<TupleElement>) tupleElements ) {
if ( alias.equals( selection.getAlias() ) ) {
index = i;
break;
}
i++;
}
}
}
if ( index < 0 ) {
throw new IllegalArgumentException(
"Given alias [" + alias + "] did not correspond to an element in the result tuple"
);
}
// index should be "in range" by nature of size check in ctor
return tuples[index];
}
public <X> X get(String alias, Class<X> type) {
final Object untyped = get( alias );
if ( untyped != null ) {
if ( !type.isInstance( untyped ) ) {
throw new IllegalArgumentException(
String.format(
"Requested tuple value [alias=%s, value=%s] cannot be assigned to requested type [%s]",
alias,
untyped,
type.getName()
)
);
}
}
return (X) untyped;
}
public Object get(int i) {
if ( i >= tuples.length ) {
throw new IllegalArgumentException(
"Given index [" + i + "] was outside the range of result tuple size [" + tuples.length + "] "
);
}
return tuples[i];
}
public <X> X get(int i, Class<X> type) {
final Object result = get( i );
if ( result != null && !type.isInstance( result ) ) {
throw new IllegalArgumentException(
String.format(
"Requested tuple value [index=%s, realType=%s] cannot be assigned to requested type [%s]",
i,
result.getClass().getName(),
type.getName()
)
);
}
return (X) result;
}
public Object[] toArray() {
// todo : make a copy?
return tuples;
}
public List<TupleElement<?>> getElements() {
return tupleElements;
}
}
}

View File

@ -6,8 +6,6 @@
*/ */
package org.hibernate.jpa.spi; package org.hibernate.jpa.spi;
import org.hibernate.procedure.spi.ParameterRegistrationImplementor;
/** /**
* ParameterRegistration extension specifically for stored procedure parameters * ParameterRegistration extension specifically for stored procedure parameters
* exposing some functionality of Hibernate's native * exposing some functionality of Hibernate's native

View File

@ -15,6 +15,7 @@ import org.hibernate.HibernateException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;

View File

@ -15,6 +15,7 @@ import org.hibernate.HibernateException;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.LoadQueryInfluencers; import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;

View File

@ -23,6 +23,7 @@ import org.hibernate.Session;
import org.hibernate.cache.spi.QueryKey; import org.hibernate.cache.spi.QueryKey;
import org.hibernate.cache.spi.QueryResultsCache; import org.hibernate.cache.spi.QueryResultsCache;
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.hql.internal.HolderInstantiator; import org.hibernate.hql.internal.HolderInstantiator;

View File

@ -9,6 +9,7 @@ package org.hibernate.loader.custom.sql;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;
import org.hibernate.param.ParameterBinder; import org.hibernate.param.ParameterBinder;

View File

@ -9,6 +9,7 @@ package org.hibernate.loader.custom.sql;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;
import org.hibernate.param.ParameterBinder; import org.hibernate.param.ParameterBinder;

View File

@ -0,0 +1,45 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.internal;
import java.io.Serializable;
import java.util.List;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.entity.DynamicBatchingEntityLoaderBuilder;
import org.hibernate.loader.spi.MultiIdEntityLoader;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.MultiLoadOptions;
import org.hibernate.persister.entity.OuterJoinLoadable;
/**
* @author Steve Ebersole
*/
public class MultiIdEntityLoaderStandardImpl<T> implements MultiIdEntityLoader<T> {
private final EntityPersister entityDescriptor;
public MultiIdEntityLoaderStandardImpl(EntityPersister entityDescriptor) {
this.entityDescriptor = entityDescriptor;
}
@Override
public EntityPersister getLoadable() {
return entityDescriptor;
}
@Override
public List<T> load(Object[] ids, MultiLoadOptions loadOptions, SharedSessionContractImplementor session) {
//noinspection unchecked
return DynamicBatchingEntityLoaderBuilder.INSTANCE.multiLoad(
(OuterJoinLoadable) entityDescriptor,
(Serializable[]) ids,
session,
loadOptions
);
}
}

View File

@ -0,0 +1,34 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.internal;
import org.hibernate.NotYetImplementedFor6Exception;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.spi.NaturalIdLoader;
import org.hibernate.persister.entity.EntityPersister;
/**
* @author Steve Ebersole
*/
public class NaturalIdLoaderStandardImpl<T> implements NaturalIdLoader<T> {
private final EntityPersister entityDescriptor;
public NaturalIdLoaderStandardImpl(EntityPersister entityDescriptor) {
this.entityDescriptor = entityDescriptor;
}
@Override
@SuppressWarnings("unchecked")
public EntityPersister getLoadable() {
return entityDescriptor;
}
@Override
public T load(Object naturalIdToLoad, LoadOptions options, SharedSessionContractImplementor session) {
throw new NotYetImplementedFor6Exception( getClass() );
}
}

View File

@ -4,14 +4,11 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.query.sqm.mutation.spi.idtable; package org.hibernate.loader.internal;
/** /**
* Actions to perform in regards to an id-table prior to each use.
*
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public enum BeforeUseAction { public interface Preparable {
CREATE, void prepare();
NONE
} }

View File

@ -0,0 +1,44 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.internal;
import org.hibernate.LockOptions;
import org.hibernate.NotYetImplementedFor6Exception;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.spi.SingleIdEntityLoader;
import org.hibernate.persister.entity.EntityPersister;
/**
* Implementation of SingleIdEntityLoader for cases where the application has
* provided the select load query
*
* @author Steve Ebersole
*/
public class SingleIdEntityLoaderProvidedQueryImpl<T> implements SingleIdEntityLoader<T> {
private final EntityPersister entityDescriptor;
private final String loadQueryName;
public SingleIdEntityLoaderProvidedQueryImpl(EntityPersister entityDescriptor, String loadQueryName) {
this.entityDescriptor = entityDescriptor;
this.loadQueryName = loadQueryName;
}
@Override
public EntityPersister getLoadable() {
return entityDescriptor;
}
@Override
public T load(Object pkValue, LockOptions lockOptions, SharedSessionContractImplementor session) {
throw new NotYetImplementedFor6Exception( getClass() );
}
@Override
public Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) {
return new Object[0];
}
}

View File

@ -0,0 +1,140 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.internal;
import java.util.EnumMap;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.NotYetImplementedFor6Exception;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.spi.InternalFetchProfile;
import org.hibernate.loader.spi.SingleIdEntityLoader;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.sql.exec.spi.JdbcSelect;
/**
* Standard implementation of SingleIdEntityLoader
*
* @author Steve Ebersole
*/
public class SingleIdEntityLoaderStandardImpl<T> implements SingleIdEntityLoader<T>, Preparable {
private final EntityPersister entityDescriptor;
private EnumMap<LockMode, JdbcSelect> selectByLockMode = new EnumMap<>( LockMode.class );
private EnumMap<InternalFetchProfile,JdbcSelect> selectByInternalCascadeProfile;
public SingleIdEntityLoaderStandardImpl(EntityPersister entityDescriptor) {
this.entityDescriptor = entityDescriptor;
}
public void prepare() {
// see `org.hibernate.persister.entity.AbstractEntityPersister#createLoaders`
}
@Override
public EntityPersister getLoadable() {
return entityDescriptor;
}
@Override
public T load(Object key, LockOptions lockOptions, SharedSessionContractImplementor session) {
// todo (6.0) : see `org.hibernate.loader.internal.StandardSingleIdEntityLoader#load` in "upstream" 6.0 branch
// - and integrate as much as possible with the `o.h.loader.plan` stuff leveraging the similarities
// between the legacy LoadPlan stuff and DomainResult, Assembler, etc.
final JdbcSelect jdbcSelect = resolveJdbcSelect( lockOptions, session );
throw new NotYetImplementedFor6Exception( getClass() );
}
@Override
public Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) {
throw new NotYetImplementedFor6Exception( getClass() );
}
private JdbcSelect resolveJdbcSelect(
LockOptions lockOptions,
SharedSessionContractImplementor session) {
final LoadQueryInfluencers loadQueryInfluencers = session.getLoadQueryInfluencers();
if ( entityDescriptor.isAffectedByEnabledFilters( loadQueryInfluencers ) ) {
// special case of not-cacheable based on enabled filters effecting this load.
//
// This case is special because the filters need to be applied in order to
// properly restrict the SQL/JDBC results. For this reason it has higher
// precedence than even "internal" fetch profiles.
return createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() );
}
final InternalFetchProfile enabledInternalFetchProfile = loadQueryInfluencers.getEnabledInternalFetchProfile();
if ( enabledInternalFetchProfile != null ) {
if ( LockMode.UPGRADE.greaterThan( lockOptions.getLockMode() ) ) {
if ( selectByInternalCascadeProfile == null ) {
selectByInternalCascadeProfile = new EnumMap<>( InternalFetchProfile.class );
}
return selectByInternalCascadeProfile.computeIfAbsent(
loadQueryInfluencers.getEnabledInternalFetchProfile(),
internalFetchProfileType -> createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() )
);
}
}
// otherwise see if the loader for the requested load can be cached - which
// also means we should look in the cache for an existing one
final boolean cacheable = determineIfCacheable( lockOptions, loadQueryInfluencers );
if ( cacheable ) {
return selectByLockMode.computeIfAbsent(
lockOptions.getLockMode(),
lockMode -> createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() )
);
}
return createJdbcSelect( lockOptions, loadQueryInfluencers, session.getFactory() );
}
private boolean determineIfCacheable(LockOptions lockOptions, LoadQueryInfluencers loadQueryInfluencers) {
if ( entityDescriptor.isAffectedByEntityGraph( loadQueryInfluencers ) ) {
return false;
}
if ( entityDescriptor.isAffectedByEnabledFetchProfiles( loadQueryInfluencers ) ) {
return false;
}
//noinspection RedundantIfStatement
if ( lockOptions.getTimeOut() != LockOptions.WAIT_FOREVER ) {
return false;
}
return true;
}
private JdbcSelect createJdbcSelect(
LockOptions lockOptions,
LoadQueryInfluencers queryInfluencers,
SessionFactoryImplementor sessionFactory) {
throw new NotYetImplementedFor6Exception( getClass() );
// final MetamodelSelectBuilder selectBuilder = new SelectByEntityIdentifierBuilder(
// entityDescriptor.getFactory(),
// entityDescriptor
// );
// final SqlAstSelectDescriptor selectDescriptor = selectBuilder
// .generateSelectStatement( 1, queryInfluencers, lockOptions );
//
//
// return SqlAstSelectToJdbcSelectConverter.interpret(
// selectDescriptor,
// sessionFactory
// );
}
}

View File

@ -11,6 +11,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.plan.exec.query.spi.NamedParameterContext; import org.hibernate.loader.plan.exec.query.spi.NamedParameterContext;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;

View File

@ -14,7 +14,6 @@ import java.util.List;
import org.hibernate.cfg.NotYetImplementedException; import org.hibernate.cfg.NotYetImplementedException;
import org.hibernate.dialect.pagination.LimitHelper; import org.hibernate.dialect.pagination.LimitHelper;
import org.hibernate.engine.spi.PersistenceContext;
import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.RowSelection; import org.hibernate.engine.spi.RowSelection;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -175,8 +174,7 @@ public class ResultSetProcessorImpl implements ResultSetProcessor {
} }
persistenceContext persistenceContext
.getLoadContexts() .getLoadContexts()
.getCollectionLoadContext( resultSet ) .findLoadingCollectionEntry( new CollectionKey( persister, key ) ).getCollectionInstance();
.getLoadingCollection( persister, key );
} }
} }

View File

@ -8,6 +8,7 @@ package org.hibernate.loader.plan.exec.process.spi;
import org.hibernate.LockMode; import org.hibernate.LockMode;
import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.loader.plan.exec.spi.LockModeResolver; import org.hibernate.loader.plan.exec.spi.LockModeResolver;
import org.hibernate.loader.plan.spi.EntityReference; import org.hibernate.loader.plan.spi.EntityReference;

View File

@ -8,6 +8,7 @@ package org.hibernate.loader.plan.exec.process.spi;
import java.sql.ResultSet; import java.sql.ResultSet;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
/** /**

View File

@ -0,0 +1,46 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.internal.util.StringHelper;
/**
* @author Steve Ebersole
*/
public enum InternalFetchProfile {
MERGE( "merge" ),
REFRESH( "refresh" );
private final String legacyName;
InternalFetchProfile(String legacyName) {
this.legacyName = legacyName;
}
public String getLegacyName() {
return legacyName;
}
public static InternalFetchProfile fromLegacyName(String legacyName) {
if ( StringHelper.isEmpty( legacyName ) ) {
return null;
}
if ( MERGE.legacyName.equalsIgnoreCase( legacyName ) ) {
return MERGE;
}
if ( REFRESH.legacyName.equalsIgnoreCase( legacyName ) ) {
return REFRESH;
}
throw new IllegalArgumentException(
"Passed name [" + legacyName + "] not recognized as a legacy internal fetch profile name; " +
"supported values include: 'merge' and 'refresh'"
);
}
}

View File

@ -0,0 +1,25 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.engine.spi.LoadQueryInfluencers;
import org.hibernate.metamodel.model.mapping.spi.ModelPart;
/**
* Contract for things that can be loaded by a Loader.
*
* Generally speaking this is limited to entities and collections
*
* @see Loader
*
* @author Steve Ebersole
*/
public interface Loadable<T> extends ModelPart<T> {
boolean isAffectedByEnabledFilters(LoadQueryInfluencers influencers);
boolean isAffectedByEntityGraph(LoadQueryInfluencers influencers);
boolean isAffectedByEnabledFetchProfiles(LoadQueryInfluencers influencers);
}

View File

@ -4,15 +4,16 @@
* License: GNU Lesser General Public License (LGPL), version 2.1 or later * License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html * See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/ */
package org.hibernate.query.sqm.mutation.spi.idtable; package org.hibernate.loader.spi;
/** /**
* Actions to perform in regards to an id-table after each use. * Common contract for all value-mapping loaders.
* *
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public enum AfterUseAction { public interface Loader<T> {
CLEAN, /**
DROP, * The value-mapping loaded by this loader
NONE */
Loadable<T> getLoadable();
} }

View File

@ -0,0 +1,26 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import java.util.List;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.persister.entity.MultiLoadOptions;
/**
* Loader subtype for loading multiple entities by multiple identifier values.
*
* @author Steve Ebersole
*/
public interface MultiIdEntityLoader<T> extends Loader<T> {
@Override
@SuppressWarnings("unchecked")
EntityPersister getLoadable();
List<T> load(Object[] ids, MultiLoadOptions options, SharedSessionContractImplementor session);
}

View File

@ -0,0 +1,45 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
* Loader for {@link org.hibernate.annotations.NaturalId} handling
*
* @author Steve Ebersole
*/
public interface NaturalIdLoader<T> extends Loader<T> {
interface LoadOptions {
/**
* The locking options for the loaded entity
*/
LockOptions getLockOptions();
/**
* Whether Hibernate should perform "synchronization" prior to performing
* look-ups?
*/
boolean isSynchronizationEnabled();
}
/**
* Perform the load of the entity by its natural-id
*
* @param naturalIdToLoad The natural-id to load. One of 2 forms accepted:
* * Single-value - valid for entities with a simple (single-valued)
* natural-id
* * Map - valid for any natural-id load. The map is each value keyed
* by the attribute name that the value corresponds to. Even though
* this form is allowed for simple natural-ids, the single value form
* should be used as it is more efficient
* @param options The options to apply to the load operation
* @param session The session into which the entity is being loaded
*/
T load(Object naturalIdToLoad, LoadOptions options, SharedSessionContractImplementor session);
}

View File

@ -0,0 +1,27 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.persister.entity.EntityPersister;
/**
* Loader for loading a single entity by primary or unique key
*
* @author Steve Ebersole
*/
public interface SingleEntityLoader<T> extends Loader<T> {
@Override
@SuppressWarnings("unchecked")
EntityPersister getLoadable();
/**
* Load an entity by a primary or unique key value.
*/
T load(Object key, LockOptions lockOptions, SharedSessionContractImplementor session);
}

View File

@ -0,0 +1,28 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
* Loader for loading an entity by a single identifier value.
*
* @author Steve Ebersole
*/
public interface SingleIdEntityLoader<T> extends SingleEntityLoader<T> {
/**
* Load by primary key value
*/
@Override
T load(Object pkValue, LockOptions lockOptions, SharedSessionContractImplementor session);
/**
* Load database snapshot by primary key value
*/
Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session);
}

View File

@ -0,0 +1,23 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.loader.spi;
import org.hibernate.LockOptions;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
/**
* Loader subtype for loading an entity by a single unique-key value.
*
* @author Steve Ebersole
*/
public interface SingleUniqueKeyEntityLoader<T> extends SingleEntityLoader {
/**
* Load by unique key value
*/
@Override
T load(Object ukValue, LockOptions lockOptions, SharedSessionContractImplementor session);
}

View File

@ -18,5 +18,5 @@ import org.hibernate.query.Query;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
@Incubating @Incubating
public interface AllowableParameterType<J> extends Writeable<J> { public interface AllowableParameterType<J> extends Writeable {
} }

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.metamodel.model.mapping.spi; package org.hibernate.metamodel.model.mapping.spi;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer; import java.util.function.Consumer;
import org.hibernate.NotYetImplementedFor6Exception; import org.hibernate.NotYetImplementedFor6Exception;
@ -20,6 +21,16 @@ import org.hibernate.type.spi.TypeConfiguration;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface Writeable { public interface Writeable {
default int getJdbcTypeCount(TypeConfiguration typeConfiguration) {
final AtomicInteger value = new AtomicInteger( 0 );
visitJdbcTypes(
sqlExpressableType -> value.incrementAndGet(),
Clause.IRRELEVANT,
typeConfiguration
);
return value.get();
}
/** /**
* Visit all of the SqlExpressableTypes associated with this this Writeable. * Visit all of the SqlExpressableTypes associated with this this Writeable.

Some files were not shown because too many files have changed in this diff Show More