HHH-2860 - Consolidate Session creation options/parameters

This commit is contained in:
Steve Ebersole 2011-03-31 15:20:33 -05:00
parent 8e2619c31e
commit df9d8939bb
27 changed files with 905 additions and 668 deletions

View File

@ -90,6 +90,13 @@ import org.hibernate.stat.SessionStatistics;
* @author Gavin King * @author Gavin King
*/ */
public interface Session extends SharedSessionContract { public interface Session extends SharedSessionContract {
/**
* Obtain a {@link Session} builder with the ability to grab certain information from this session.
*
* @return The session builder
*/
public SharedSessionBuilder sessionWithOptions();
/** /**
* Retrieve the entity mode in effect for this session. * Retrieve the entity mode in effect for this session.
* *
@ -105,7 +112,9 @@ public interface Session extends SharedSessionContract {
* *
* @param entityMode The entity mode to use for the new session. * @param entityMode The entity mode to use for the new session.
* @return The new session * @return The new session
* @deprecated
*/ */
@Deprecated
public Session getSession(EntityMode entityMode); public Session getSession(EntityMode entityMode);
/** /**
@ -170,21 +179,6 @@ public interface Session extends SharedSessionContract {
*/ */
public SessionFactory getSessionFactory(); public SessionFactory getSessionFactory();
/**
* Get the JDBC connection of this Session.<br>
* <br>
* If the session is using aggressive collection release (as in a
* CMT environment), it is the application's responsibility to
* close the connection returned by this call. Otherwise, the
* application should not close the connection.
*
* @return the JDBC connection in use by the <tt>Session</tt>
* @throws HibernateException if the <tt>Session</tt> is disconnected
* @deprecated (scheduled for removal in 4.x). Replacement depends on need; for doing direct JDBC stuff use
* {@link #doWork}; for opening a 'temporary Session' use (TBD).
*/
public Connection connection() throws HibernateException;
/** /**
* End the session by releasing the JDBC connection and cleaning up. It is * End the session by releasing the JDBC connection and cleaning up. It is
* not strictly necessary to close the session but you must at least * not strictly necessary to close the session but you must at least
@ -856,8 +850,6 @@ public interface Session extends SharedSessionContract {
* *
* @return the application-supplied connection or {@literal null} * @return the application-supplied connection or {@literal null}
* *
* @see SessionFactory#openSession(java.sql.Connection)
* @see SessionFactory#openSession(java.sql.Connection, Interceptor)
* @see #reconnect(Connection) * @see #reconnect(Connection)
*/ */
Connection disconnect() throws HibernateException; Connection disconnect() throws HibernateException;
@ -866,6 +858,7 @@ public interface Session extends SharedSessionContract {
* Reconnect to the given JDBC connection. * Reconnect to the given JDBC connection.
* *
* @param connection a JDBC connection * @param connection a JDBC connection
*
* @see #disconnect() * @see #disconnect()
*/ */
void reconnect(Connection connection) throws HibernateException; void reconnect(Connection connection) throws HibernateException;
@ -971,11 +964,11 @@ public interface Session extends SharedSessionContract {
/** /**
* Specify if LockMode should be cascaded to owned collections and relationships. * Specify if LockMode should be cascaded to owned collections and relationships.
* The association must be mapped with <tt>cascade="lock" for scope=true to work. * The association must be mapped with {@code cascade="lock"} for scope=true to work.
* *
* @param scope * @param scope {@code true} to cascade locks; {@code false} to not.
* *
* @return * @return {@code this}, for method chaining
*/ */
LockRequest setScope(boolean scope); LockRequest setScope(boolean scope);

View File

@ -0,0 +1,103 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate;
import java.sql.Connection;
/**
* Represents a consolidation of all session creation options into a builder style delegate.
*
* @author Steve Ebersole
*/
public interface SessionBuilder {
/**
* Opens a session with the specified options.
*
* @return The session
*/
public Session openSession();
/**
* Adds a specific interceptor to the session options
*
* @param interceptor The interceptor to use.
*
* @return {@code this}, for method chaining
*/
public SessionBuilder interceptor(Interceptor interceptor);
/**
* Adds a specific connection to the session options
*
* @param connection The connection to use.
*
* @return {@code this}, for method chaining
*/
public SessionBuilder connection(Connection connection);
/**
* Use a specific connection release mode for these session options
*
* @param connectionReleaseMode The connection release mode to use.
*
* @return {@code this}, for method chaining
*/
public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
/**
* Use a specific entity mode for these session options
*
* @param entityMode The entity mode to use.
*
* @return {@code this}, for method chaining
*/
public SessionBuilder entityMode(EntityMode entityMode);
/**
* Should the session built automatically join in any ongoing JTA transactions
*
* @param autoJoinTransactions Should JTA transactions be automatically joined
*
* @return {@code this}, for method chaining
*/
public SessionBuilder autoJoinTransactions(boolean autoJoinTransactions);
/**
* Should the session be automatically closed after transaction completion
*
* @param autoClose Should the session be automatically closed
*
* @return {@code this}, for method chaining
*/
public SessionBuilder autoClose(boolean autoClose);
/**
* Should the session be automatically flushed during the "before completion" phase of transaction handling.
*
* @param flushBeforeCompletion Should the session be automatically flushed
*
* @return {@code this}, for method chaining
*/
public SessionBuilder flushBeforeCompletion(boolean flushBeforeCompletion);
}

View File

@ -51,6 +51,13 @@ import org.hibernate.stat.Statistics;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public interface SessionFactory extends Referenceable, Serializable { public interface SessionFactory extends Referenceable, Serializable {
/**
* Obtain a {@link Session} builder.
*
* @return The session builder
*/
public SessionBuilder withOptions();
/** /**
* Open a {@link Session}. * Open a {@link Session}.
* <p/> * <p/>
@ -60,57 +67,10 @@ public interface SessionFactory extends Referenceable, Serializable {
* *
* @return The created session. * @return The created session.
* *
* @throws HibernateException Indicates a peroblem opening the session; pretty rare here. * @throws HibernateException Indicates a problem opening the session; pretty rare here.
*/ */
public Session openSession() throws HibernateException; public Session openSession() throws HibernateException;
/**
* Open a {@link Session}, utilizing the specified {@link Interceptor}.
* <p/>
* JDBC {@link Connection connection(s} will be obtained from the
* configured {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} as needed
* to perform requested work.
*
* @param interceptor a session-scoped interceptor
*
* @return The created session.
*
* @throws HibernateException Indicates a peroblem opening the session; pretty rare here.
*/
public Session openSession(Interceptor interceptor) throws HibernateException;
/**
* Open a {@link Session}, utilizing the specfied JDBC {@link Connection}.
* <p>
* Note that the second-level cache will be disabled if you supply a JDBC
* connection. Hibernate will not be able to track any statements you might
* have executed in the same transaction. Consider implementing your own
* {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly
* recommended alternative.
*
* @param connection a connection provided by the application.
*
* @return The created session.
*/
public Session openSession(Connection connection);
/**
* Open a {@link Session}, utilizing the specfied JDBC {@link Connection} and
* specified {@link Interceptor}.
* <p>
* Note that the second-level cache will be disabled if you supply a JDBC
* connection. Hibernate will not be able to track any statements you might
* have executed in the same transaction. Consider implementing your own
* {@link org.hibernate.service.jdbc.connections.spi.ConnectionProvider} instead as a highly
* recommended alternative.
*
* @param connection a connection provided by the application.
* @param interceptor a session-scoped interceptor
*
* @return The created session.
*/
public Session openSession(Connection connection, Interceptor interceptor);
/** /**
* Obtains the current session. The definition of what exactly "current" * Obtains the current session. The definition of what exactly "current"
* means controlled by the {@link org.hibernate.context.CurrentSessionContext} impl configured * means controlled by the {@link org.hibernate.context.CurrentSessionContext} impl configured

View File

@ -0,0 +1,70 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate;
import java.sql.Connection;
/**
* Specialized {@link SessionBuilder} with access to stuff from another session
*
* @author Steve Ebersole
*/
public interface SharedSessionBuilder extends SessionBuilder {
public SharedSessionBuilder interceptor();
public SharedSessionBuilder connection();
public SharedSessionBuilder connectionReleaseMode();
public SharedSessionBuilder entityMode();
public SharedSessionBuilder autoJoinTransactions();
public SharedSessionBuilder autoClose();
public SharedSessionBuilder flushBeforeCompletion();
public SharedSessionBuilder transactionContext();
@Override
SharedSessionBuilder interceptor(Interceptor interceptor);
@Override
SharedSessionBuilder connection(Connection connection);
@Override
SharedSessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode);
@Override
SharedSessionBuilder entityMode(EntityMode entityMode);
@Override
SharedSessionBuilder autoJoinTransactions(boolean autoJoinTransactions);
@Override
SharedSessionBuilder autoClose(boolean autoClose);
@Override
SharedSessionBuilder flushBeforeCompletion(boolean flushBeforeCompletion);
}

View File

@ -146,12 +146,11 @@ public class JTASessionContext implements CurrentSessionContext {
* @return the built or (re)obtained session. * @return the built or (re)obtained session.
*/ */
protected Session buildOrObtainSession() { protected Session buildOrObtainSession() {
return factory.openSession( return factory.withOptions()
null, .autoClose( isAutoCloseEnabled() )
isAutoFlushEnabled(), .connectionReleaseMode( getConnectionReleaseMode() )
isAutoCloseEnabled(), .flushBeforeCompletion( isAutoFlushEnabled() )
getConnectionReleaseMode() .openSession();
);
} }
/** /**

View File

@ -145,12 +145,11 @@ public class ThreadLocalSessionContext implements CurrentSessionContext {
* @return the built or (re)obtained session. * @return the built or (re)obtained session.
*/ */
protected Session buildOrObtainSession() { protected Session buildOrObtainSession() {
return factory.openSession( return factory.withOptions()
null, .autoClose( isAutoCloseEnabled() )
isAutoFlushEnabled(), .connectionReleaseMode( getConnectionReleaseMode() )
isAutoCloseEnabled(), .flushBeforeCompletion( isAutoFlushEnabled() )
getConnectionReleaseMode() .openSession();
);
} }
protected CleanupSynch buildCleanupSynch() { protected CleanupSynch buildCleanupSynch() {

View File

@ -217,29 +217,6 @@ public interface SessionFactoryImplementor extends Mapping, SessionFactory {
*/ */
public Session openTemporarySession() throws HibernateException; public Session openTemporarySession() throws HibernateException;
public Session openSession(boolean autoJoinTransaction);
public Session openSession(Interceptor sessionLocalInterceptor, boolean autoJoinTransaction);
/**
* Open a session conforming to the given parameters. Used mainly by
* {@link org.hibernate.context.JTASessionContext} for current session processing.
*
* @param connection The external jdbc connection to use, if one (i.e., optional).
* @param flushBeforeCompletionEnabled Should the session be auto-flushed
* prior to transaction completion?
* @param autoCloseSessionEnabled Should the session be auto-closed after
* transaction completion?
* @param connectionReleaseMode The release mode for managed jdbc connections.
* @return An appropriate session.
* @throws HibernateException
*/
public Session openSession(
final Connection connection,
final boolean flushBeforeCompletionEnabled,
final boolean autoCloseSessionEnabled,
final ConnectionReleaseMode connectionReleaseMode) throws HibernateException;
/** /**
* Retrieves a set of all the collection roles in which the given entity * Retrieves a set of all the collection roles in which the given entity
* is a participant, as either an index or an element. * is a participant, as either an index or an element.

View File

@ -62,6 +62,7 @@ import org.hibernate.MappingException;
import org.hibernate.ObjectNotFoundException; import org.hibernate.ObjectNotFoundException;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver; import org.hibernate.SessionFactoryObserver;
import org.hibernate.StatelessSession; import org.hibernate.StatelessSession;
@ -101,6 +102,7 @@ import org.hibernate.engine.profile.Fetch;
import org.hibernate.engine.profile.FetchProfile; import org.hibernate.engine.profile.FetchProfile;
import org.hibernate.engine.query.QueryPlanCache; import org.hibernate.engine.query.QueryPlanCache;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification; import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl;
import org.hibernate.engine.transaction.spi.TransactionEnvironment; import org.hibernate.engine.transaction.spi.TransactionEnvironment;
import org.hibernate.exception.SQLExceptionConverter; import org.hibernate.exception.SQLExceptionConverter;
import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.IdentifierGenerator;
@ -129,7 +131,6 @@ import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.hibernate.service.spi.SessionFactoryServiceRegistry; import org.hibernate.service.spi.SessionFactoryServiceRegistry;
import org.hibernate.service.spi.SessionFactoryServiceRegistryFactory; import org.hibernate.service.spi.SessionFactoryServiceRegistryFactory;
import org.hibernate.stat.Statistics; import org.hibernate.stat.Statistics;
import org.hibernate.stat.internal.ConcurrentStatisticsImpl;
import org.hibernate.stat.spi.StatisticsImplementor; import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate; import org.hibernate.tool.hbm2ddl.SchemaUpdate;
@ -528,6 +529,38 @@ public final class SessionFactoryImpl
return integrators; return integrators;
} }
public Session openSession() throws HibernateException {
return withOptions().openSession();
}
public Session openTemporarySession() throws HibernateException {
return withOptions()
.autoClose( false )
.flushBeforeCompletion( false )
.connectionReleaseMode( ConnectionReleaseMode.AFTER_STATEMENT )
.openSession();
}
public Session getCurrentSession() throws HibernateException {
if ( currentSessionContext == null ) {
throw new HibernateException( "No CurrentSessionContext configured!" );
}
return currentSessionContext.currentSession();
}
@Override
public SessionBuilder withOptions() {
return new SessionBuilderImpl( this );
}
public StatelessSession openStatelessSession() {
return new StatelessSessionImpl( null, this );
}
public StatelessSession openStatelessSession(Connection connection) {
return new StatelessSessionImpl( connection, this );
}
@Override @Override
public void addObserver(SessionFactoryObserver observer) { public void addObserver(SessionFactoryObserver observer) {
this.observer.addObserver( observer ); this.observer.addObserver( observer );
@ -658,118 +691,6 @@ public final class SessionFactoryImpl
return errors; return errors;
} }
public StatelessSession openStatelessSession() {
return new StatelessSessionImpl( null, this );
}
public StatelessSession openStatelessSession(Connection connection) {
return new StatelessSessionImpl( connection, this );
}
private SessionImpl openSession(
Connection connection,
boolean autoClose,
long timestamp,
Interceptor sessionLocalInterceptor) {
return openSession(
connection,
autoClose,
true,
timestamp,
sessionLocalInterceptor
);
}
private SessionImpl openSession(
Connection connection,
boolean autoClose,
boolean autoJoinTransactions,
long timestamp,
Interceptor sessionLocalInterceptor) {
return new SessionImpl(
connection,
this,
autoClose,
autoJoinTransactions,
timestamp,
sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor,
settings.getDefaultEntityMode(),
settings.isFlushBeforeCompletionEnabled(),
settings.isAutoCloseSessionEnabled(),
settings.getConnectionReleaseMode()
);
}
public Session openSession(Connection connection, Interceptor sessionLocalInterceptor) {
return openSession( connection, false, Long.MIN_VALUE, sessionLocalInterceptor );
}
public Session openSession(Interceptor sessionLocalInterceptor) throws HibernateException {
return openSession( sessionLocalInterceptor, true );
}
public Session openSession(boolean autoJoinTransaction) {
return openSession( null, autoJoinTransaction );
}
public Session openSession(Interceptor sessionLocalInterceptor, boolean autoJoinTransaction) {
// note that this timestamp is not correct if the connection provider
// returns an older JDBC connection that was associated with a
// transaction that was already begun before openSession() was called
// (don't know any possible solution to this!)
long timestamp = settings.getRegionFactory().nextTimestamp();
return openSession( null, true, autoJoinTransaction, timestamp, sessionLocalInterceptor );
}
public Session openSession(Connection connection) {
return openSession(connection, interceptor); //prevents this session from adding things to cache
}
public Session openSession() throws HibernateException {
return openSession(interceptor);
}
public Session openTemporarySession() throws HibernateException {
return new SessionImpl(
null,
this,
true,
true,
settings.getRegionFactory().nextTimestamp(),
interceptor,
settings.getDefaultEntityMode(),
false,
false,
ConnectionReleaseMode.AFTER_STATEMENT
);
}
public Session openSession(
final Connection connection,
final boolean flushBeforeCompletionEnabled,
final boolean autoCloseSessionEnabled,
final ConnectionReleaseMode connectionReleaseMode) throws HibernateException {
return new SessionImpl(
connection,
this,
true,
true,
settings.getRegionFactory().nextTimestamp(),
interceptor,
settings.getDefaultEntityMode(),
flushBeforeCompletionEnabled,
autoCloseSessionEnabled,
connectionReleaseMode
);
}
public Session getCurrentSession() throws HibernateException {
if ( currentSessionContext == null ) {
throw new HibernateException( "No CurrentSessionContext configured!" );
}
return currentSessionContext.currentSession();
}
public EntityPersister getEntityPersister(String entityName) throws MappingException { public EntityPersister getEntityPersister(String entityName) throws MappingException {
EntityPersister result = (EntityPersister) entityPersisters.get(entityName); EntityPersister result = (EntityPersister) entityPersisters.get(entityName);
if (result==null) { if (result==null) {
@ -1391,4 +1312,89 @@ public final class SessionFactoryImpl
} }
return ( SessionFactoryImpl ) result; return ( SessionFactoryImpl ) result;
} }
static class SessionBuilderImpl implements SessionBuilder {
private final SessionFactoryImpl sessionFactory;
private Interceptor interceptor;
private Connection connection;
private ConnectionReleaseMode connectionReleaseMode;
private EntityMode entityMode;
private boolean autoClose;
private boolean autoJoinTransactions = true;
private boolean flushBeforeCompletion;
SessionBuilderImpl(SessionFactoryImpl sessionFactory) {
this.sessionFactory = sessionFactory;
final Settings settings = sessionFactory.settings;
// set up default builder values...
this.interceptor = sessionFactory.getInterceptor();
this.connectionReleaseMode = settings.getConnectionReleaseMode();
this.entityMode = settings.getDefaultEntityMode();
this.autoClose = settings.isAutoCloseSessionEnabled();
this.flushBeforeCompletion = settings.isFlushBeforeCompletionEnabled();
}
protected TransactionCoordinatorImpl getTransactionCoordinator() {
return null;
}
@Override
public Session openSession() {
return new SessionImpl(
connection,
sessionFactory,
getTransactionCoordinator(),
autoJoinTransactions,
sessionFactory.settings.getRegionFactory().nextTimestamp(),
interceptor,
entityMode,
flushBeforeCompletion,
autoClose,
connectionReleaseMode
);
}
@Override
public SessionBuilder interceptor(Interceptor interceptor) {
this.interceptor = interceptor;
return this;
}
@Override
public SessionBuilder connection(Connection connection) {
this.connection = connection;
return this;
}
@Override
public SessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode) {
this.connectionReleaseMode = connectionReleaseMode;
return this;
}
@Override
public SessionBuilder autoJoinTransactions(boolean autoJoinTransactions) {
this.autoJoinTransactions = autoJoinTransactions;
return this;
}
@Override
public SessionBuilder autoClose(boolean autoClose) {
this.autoClose = autoClose;
return this;
}
@Override
public SessionBuilder flushBeforeCompletion(boolean flushBeforeCompletion) {
this.flushBeforeCompletion = flushBeforeCompletion;
return this;
}
@Override
public SessionBuilder entityMode(EntityMode entityMode) {
this.entityMode = entityMode;
return this;
}
}
} }

View File

@ -68,6 +68,7 @@ import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults; import org.hibernate.ScrollableResults;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionException; import org.hibernate.SessionException;
import org.hibernate.SharedSessionBuilder;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.TransientObjectException; import org.hibernate.TransientObjectException;
import org.hibernate.TypeHelper; import org.hibernate.TypeHelper;
@ -179,13 +180,14 @@ public final class SessionImpl
private transient FlushMode flushMode = FlushMode.AUTO; private transient FlushMode flushMode = FlushMode.AUTO;
private transient CacheMode cacheMode = CacheMode.NORMAL; private transient CacheMode cacheMode = CacheMode.NORMAL;
private transient EntityMode entityMode = EntityMode.POJO; private transient EntityMode entityMode = EntityMode.POJO;
private transient boolean autoClear; //for EJB3 private transient boolean autoClear; //for EJB3
private transient boolean autoJoinTransactions = true; private transient boolean autoJoinTransactions = true;
private transient int dontFlushFromFind = 0;
private transient boolean flushBeforeCompletionEnabled; private transient boolean flushBeforeCompletionEnabled;
private transient boolean autoCloseSessionEnabled; private transient boolean autoCloseSessionEnabled;
private transient int dontFlushFromFind = 0;
private transient LoadQueryInfluencers loadQueryInfluencers; private transient LoadQueryInfluencers loadQueryInfluencers;
private transient Session rootSession; private transient Session rootSession;
@ -223,7 +225,9 @@ public final class SessionImpl
* *
* @param connection The user-supplied connection to use for this session. * @param connection The user-supplied connection to use for this session.
* @param factory The factory from which this session was obtained * @param factory The factory from which this session was obtained
* @param autoClose NOT USED * @param transactionCoordinator The transaction coordinator to use, may be null to indicate that a new transaction
* coordinator should get created.
* @param autoJoinTransactions Should the session automatically join JTA transactions?
* @param timestamp The timestamp for this session * @param timestamp The timestamp for this session
* @param interceptor The interceptor to be applied to this session * @param interceptor The interceptor to be applied to this session
* @param entityMode The entity-mode for this session * @param entityMode The entity-mode for this session
@ -234,7 +238,7 @@ public final class SessionImpl
SessionImpl( SessionImpl(
final Connection connection, final Connection connection,
final SessionFactoryImpl factory, final SessionFactoryImpl factory,
final boolean autoClose, final TransactionCoordinatorImpl transactionCoordinator,
final boolean autoJoinTransactions, final boolean autoJoinTransactions,
final long timestamp, final long timestamp,
final Interceptor interceptor, final Interceptor interceptor,
@ -254,10 +258,18 @@ public final class SessionImpl
this.connectionReleaseMode = connectionReleaseMode; this.connectionReleaseMode = connectionReleaseMode;
this.autoJoinTransactions = autoJoinTransactions; this.autoJoinTransactions = autoJoinTransactions;
this.transactionCoordinator = new TransactionCoordinatorImpl( connection, this ); if ( transactionCoordinator == null ) {
this.transactionCoordinator.getJdbcCoordinator().getLogicalConnection().addObserver( this.transactionCoordinator = new TransactionCoordinatorImpl( connection, this );
new ConnectionObserverStatsBridge( factory ) this.transactionCoordinator.getJdbcCoordinator().getLogicalConnection().addObserver(
); new ConnectionObserverStatsBridge( factory )
);
}
else {
if ( connection != null ) {
throw new SessionException( "Cannot simultaneously share transaction context and specify connection" );
}
this.transactionCoordinator = transactionCoordinator;
}
loadQueryInfluencers = new LoadQueryInfluencers( factory ); loadQueryInfluencers = new LoadQueryInfluencers( factory );
@ -266,6 +278,11 @@ public final class SessionImpl
LOG.debugf("Opened session at timestamp: %s", timestamp); LOG.debugf("Opened session at timestamp: %s", timestamp);
} }
@Override
public SharedSessionBuilder sessionWithOptions() {
return new SharedSessionBuilderImpl( this );
}
public Session getSession(EntityMode entityMode) { public Session getSession(EntityMode entityMode) {
if ( this.entityMode == entityMode ) { if ( this.entityMode == entityMode ) {
return this; return this;
@ -2107,6 +2124,102 @@ public final class SessionImpl
} }
} }
private static class SharedSessionBuilderImpl extends SessionFactoryImpl.SessionBuilderImpl implements SharedSessionBuilder {
private final SessionImpl session;
private boolean shareTransactionContext;
private SharedSessionBuilderImpl(SessionImpl session) {
super( session.factory );
this.session = session;
}
@Override
protected TransactionCoordinatorImpl getTransactionCoordinator() {
return shareTransactionContext ? session.transactionCoordinator : super.getTransactionCoordinator();
}
@Override
public SharedSessionBuilder interceptor() {
return interceptor( session.interceptor );
}
@Override
public SharedSessionBuilder connection() {
return connection(
session.transactionCoordinator
.getJdbcCoordinator()
.getLogicalConnection()
.getDistinctConnectionProxy()
);
}
@Override
public SharedSessionBuilder connectionReleaseMode() {
return connectionReleaseMode( session.connectionReleaseMode );
}
@Override
public SharedSessionBuilder entityMode() {
return entityMode( session.entityMode );
}
@Override
public SharedSessionBuilder autoJoinTransactions() {
return autoJoinTransactions( session.autoJoinTransactions );
}
@Override
public SharedSessionBuilder autoClose() {
return autoClose( session.autoCloseSessionEnabled );
}
@Override
public SharedSessionBuilder flushBeforeCompletion() {
return flushBeforeCompletion( session.flushBeforeCompletionEnabled );
}
@Override
public SharedSessionBuilder transactionContext() {
this.shareTransactionContext = true;
return this;
}
@Override
public SharedSessionBuilder interceptor(Interceptor interceptor) {
return (SharedSessionBuilder) super.interceptor( interceptor );
}
@Override
public SharedSessionBuilder connection(Connection connection) {
return (SharedSessionBuilder) super.connection( connection );
}
@Override
public SharedSessionBuilder connectionReleaseMode(ConnectionReleaseMode connectionReleaseMode) {
return (SharedSessionBuilder) super.connectionReleaseMode( connectionReleaseMode );
}
@Override
public SharedSessionBuilder entityMode(EntityMode entityMode) {
return (SharedSessionBuilder) super.entityMode( entityMode );
}
@Override
public SharedSessionBuilder autoJoinTransactions(boolean autoJoinTransactions) {
return (SharedSessionBuilder) super.autoJoinTransactions( autoJoinTransactions );
}
@Override
public SharedSessionBuilder autoClose(boolean autoClose) {
return (SharedSessionBuilder) super.autoClose( autoClose );
}
@Override
public SharedSessionBuilder flushBeforeCompletion(boolean flushBeforeCompletion) {
return (SharedSessionBuilder) super.flushBeforeCompletion( flushBeforeCompletion );
}
}
private class CoordinatingEntityNameResolver implements EntityNameResolver { private class CoordinatingEntityNameResolver implements EntityNameResolver {
public String resolveEntityName(Object entity) { public String resolveEntityName(Object entity) {
String entityName = interceptor.getEntityName( entity ); String entityName = interceptor.getEntityName( entity );

View File

@ -22,21 +22,25 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.jmx; package org.hibernate.jmx;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import java.io.InvalidObjectException; import java.io.InvalidObjectException;
import java.io.ObjectStreamException; import java.io.ObjectStreamException;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.naming.NamingException;
import javax.naming.Reference; import org.jboss.logging.Logger;
import javax.naming.StringRefAddr;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
import org.hibernate.Cache; import org.hibernate.Cache;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger; import org.hibernate.HibernateLogger;
import org.hibernate.Interceptor;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory; import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession; import org.hibernate.StatelessSession;
import org.hibernate.TypeHelper; import org.hibernate.TypeHelper;
@ -47,7 +51,6 @@ import org.hibernate.impl.SessionFactoryObjectFactory;
import org.hibernate.metadata.ClassMetadata; import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata; import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.stat.Statistics; import org.hibernate.stat.Statistics;
import org.jboss.logging.Logger;
/** /**
* A flyweight for <tt>SessionFactory</tt>. If the MBean itself does not * A flyweight for <tt>SessionFactory</tt>. If the MBean itself does not
@ -79,22 +82,15 @@ public class SessionFactoryStub implements SessionFactory {
SessionFactoryObjectFactory.addInstance( uuid, name, this, service.getProperties() ); SessionFactoryObjectFactory.addInstance( uuid, name, this, service.getProperties() );
} }
public Session openSession(Connection connection, Interceptor interceptor) { @Override
return getImpl().openSession(connection, interceptor); public SessionBuilder withOptions() {
} return getImpl().withOptions();
public Session openSession(Interceptor interceptor) throws HibernateException {
return getImpl().openSession(interceptor);
} }
public Session openSession() throws HibernateException { public Session openSession() throws HibernateException {
return getImpl().openSession(); return getImpl().openSession();
} }
public Session openSession(Connection conn) {
return getImpl().openSession(conn);
}
public Session getCurrentSession() { public Session getCurrentSession() {
return getImpl().getCurrentSession(); return getImpl().getCurrentSession();
} }

View File

@ -196,7 +196,7 @@ public class AggressiveReleaseTest extends ConnectionManagementTestCase {
prepare(); prepare();
Connection originalConnection = sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).getConnection(); Connection originalConnection = sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).getConnection();
Session session = sessionFactory().openSession( originalConnection ); Session session = sessionFactory().withOptions().connection( originalConnection ).openSession();
Silly silly = new Silly( "silly" ); Silly silly = new Silly( "silly" );
session.save( silly ); session.save( silly );
@ -215,36 +215,6 @@ public class AggressiveReleaseTest extends ConnectionManagementTestCase {
sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).closeConnection( originalConnection ); sessionFactory().getServiceRegistry().getService( ConnectionProvider.class ).closeConnection( originalConnection );
} }
@Test
public void testBorrowedConnections() throws Throwable {
prepare();
Session s = getSessionUnderTest();
// todo : may need to come back here and make sure that closing the connection handles do not close the physical cached connection on LogicalConnection...
Connection conn = s.connection();
assertFalse( conn.isClosed() );
assertFalse(
((SessionImpl) s).getTransactionCoordinator()
.getJdbcCoordinator()
.getLogicalConnection()
.isPhysicallyConnected()
);
conn.getCatalog();
assertTrue(
((SessionImpl) s).getTransactionCoordinator()
.getJdbcCoordinator()
.getLogicalConnection()
.isPhysicallyConnected()
);
conn.close();
assertTrue( conn.isClosed() );
assertTrue( ( ( SessionImpl ) s ).getTransactionCoordinator().getJdbcCoordinator().getLogicalConnection().isPhysicallyConnected() );
release( s );
done();
}
@Test @Test
public void testConnectionMaintanenceDuringFlush() throws Throwable { public void testConnectionMaintanenceDuringFlush() throws Throwable {
prepare(); prepare();

View File

@ -340,13 +340,6 @@ public abstract class ConnectionManagementTestCase extends BaseCoreFunctionalTes
catch( Throwable ignore ) { catch( Throwable ignore ) {
} }
try {
s.connection();
fail( "allowed to access connection on closed session" );
}
catch( Throwable ignore ) {
}
try { try {
s.close(); s.close();
fail( "allowed to close already closed session" ); fail( "allowed to close already closed session" );

View File

@ -23,6 +23,7 @@
*/ */
package org.hibernate.test.connections; package org.hibernate.test.connections;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -35,8 +36,6 @@ import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable; import org.hibernate.service.spi.Stoppable;
import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce; import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.env.ConnectionProviderBuilder; import org.hibernate.testing.env.ConnectionProviderBuilder;
@ -70,7 +69,7 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase {
@Override @Override
protected Session getSessionUnderTest() throws Throwable { protected Session getSessionUnderTest() throws Throwable {
connectionUnderTest = cp.getConnection(); connectionUnderTest = cp.getConnection();
return sessionFactory().openSession( connectionUnderTest ); return sessionFactory().withOptions().connection( connectionUnderTest ).openSession();
} }
@Override @Override

View File

@ -22,6 +22,8 @@
* Boston, MA 02110-1301 USA * Boston, MA 02110-1301 USA
*/ */
package org.hibernate.test.join; package org.hibernate.test.join;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -29,6 +31,7 @@ import org.hibernate.Hibernate;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.AbstractWork;
import org.junit.Test; import org.junit.Test;
@ -137,7 +140,14 @@ public class JoinTest extends BaseCoreFunctionalTestCase {
s.clear(); s.clear();
// Remove the optional row from the join table and requery the User obj // Remove the optional row from the join table and requery the User obj
s.connection().prepareStatement("delete from t_user").execute(); s.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
connection.prepareStatement("delete from t_user").execute();
}
}
);
s.clear(); s.clear();
jesus = (User) s.get( Person.class, new Long( jesus.getId() ) ); jesus = (User) s.get( Person.class, new Long( jesus.getId() ) );

View File

@ -54,7 +54,7 @@ public class TransactionJoiningTest extends AbstractJPATest {
public void testExplicitJoining() throws Exception { public void testExplicitJoining() throws Exception {
assertFalse( JtaStatusHelper.isActive( TestingJtaBootstrap.INSTANCE.getTransactionManager() ) ); assertFalse( JtaStatusHelper.isActive( TestingJtaBootstrap.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().openSession( false ); SessionImplementor session = (SessionImplementor) sessionFactory().withOptions().autoJoinTransactions( false ).openSession();
TransactionImplementor transaction = (TransactionImplementor) ( (Session) session ).getTransaction(); TransactionImplementor transaction = (TransactionImplementor) ( (Session) session ).getTransaction();
assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() ); assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() );
@ -100,7 +100,7 @@ public class TransactionJoiningTest extends AbstractJPATest {
TestingJtaBootstrap.INSTANCE.getTransactionManager().begin(); TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaBootstrap.INSTANCE.getTransactionManager() ) ); assertTrue( JtaStatusHelper.isActive( TestingJtaBootstrap.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().openSession( false ); SessionImplementor session = (SessionImplementor) sessionFactory().withOptions().autoJoinTransactions( false ).openSession();
session.getFlushMode(); session.getFlushMode();
} }

View File

@ -32,68 +32,56 @@ public class CustomSQLTest extends LegacyTestCase {
} }
@Test @Test
@SuppressWarnings( {"UnnecessaryBoxing"})
public void testInsert() throws HibernateException, SQLException { public void testInsert() throws HibernateException, SQLException {
if ( isUsingIdentity() ) { if ( isUsingIdentity() ) {
SkipLog.reportSkip( "hand sql expecting non-identity id gen", "Custom SQL" ); SkipLog.reportSkip( "hand sql expecting non-identity id gen", "Custom SQL" );
return; return;
} }
Role p = new Role();
p.setName("Patient");
Session s = openSession(); Session s = openSession();
s.beginTransaction();
s.save(p); Role p = new Role();
s.flush(); p.setName("Patient");
s.save( p );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
sessionFactory().evict(Role.class); sessionFactory().getCache().evictEntityRegion( Role.class );
s = openSession();
Role p2 = (Role) s.get(Role.class, new Long(p.getId())); s = openSession();
s.beginTransaction();
Role p2 = (Role) s.get(Role.class, Long.valueOf(p.getId()));
assertNotSame(p, p2); assertNotSame(p, p2);
assertEquals(p2.getId(),p.getId()); assertEquals(p2.getId(),p.getId());
assertTrue(p2.getName().equalsIgnoreCase(p.getName())); assertTrue(p2.getName().equalsIgnoreCase(p.getName()));
s.delete(p2); s.delete(p2);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testJoinedSubclass() throws HibernateException, SQLException { public void testJoinedSubclass() throws HibernateException, SQLException {
Medication m = new Medication();
m.setPrescribedDrug(new Drug());
m.getPrescribedDrug().setName("Morphine");
Session s = openSession(); Session s = openSession();
s.beginTransaction();
s.save(m.getPrescribedDrug()); Medication m = new Medication();
s.save(m); m.setPrescribedDrug(new Drug());
m.getPrescribedDrug().setName( "Morphine" );
s.flush(); s.save( m.getPrescribedDrug() );
s.connection().commit(); s.save( m );
s.getTransaction().commit();
s.close(); s.close();
s = openSession();
s = openSession();
s.beginTransaction();
Medication m2 = (Medication) s.get(Medication.class, m.getId()); Medication m2 = (Medication) s.get(Medication.class, m.getId());
assertNotSame(m, m2); assertNotSame(m, m2);
s.getTransaction().commit();
s.flush();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
@SuppressWarnings( {"UnnecessaryBoxing", "unchecked"})
public void testCollectionCUD() throws HibernateException, SQLException { public void testCollectionCUD() throws HibernateException, SQLException {
if ( isUsingIdentity() ) { if ( isUsingIdentity() ) {
SkipLog.reportSkip( "hand sql expecting non-identity id gen", "Custom SQL" ); SkipLog.reportSkip( "hand sql expecting non-identity id gen", "Custom SQL" );
@ -101,12 +89,9 @@ public class CustomSQLTest extends LegacyTestCase {
} }
Role role = new Role(); Role role = new Role();
role.setName("Jim Flanders"); role.setName("Jim Flanders");
Intervention iv = new Medication(); Intervention iv = new Medication();
iv.setDescription("JF medical intervention"); iv.setDescription("JF medical intervention");
role.getInterventions().add(iv); role.getInterventions().add(iv);
List sx = new ArrayList(); List sx = new ArrayList();
@ -116,28 +101,23 @@ public class CustomSQLTest extends LegacyTestCase {
role.setBunchOfStrings(sx); role.setBunchOfStrings(sx);
Session s = openSession(); Session s = openSession();
s.beginTransaction();
s.save(role); s.save(role);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Role r = (Role) s.get(Role.class,new Long(role.getId())); Role r = (Role) s.get(Role.class, Long.valueOf(role.getId()));
assertNotSame(role,r); assertNotSame(role,r);
assertEquals(1,r.getInterventions().size()); assertEquals(1,r.getInterventions().size());
assertEquals(3, r.getBunchOfStrings().size()); assertEquals(3, r.getBunchOfStrings().size());
r.getBunchOfStrings().set(1, "replacement"); r.getBunchOfStrings().set(1, "replacement");
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
r = (Role) s.get(Role.class,new Long(role.getId())); r = (Role) s.get(Role.class,new Long(role.getId()));
assertNotSame(role,r); assertNotSame(role,r);
@ -150,11 +130,8 @@ public class CustomSQLTest extends LegacyTestCase {
s.flush(); s.flush();
r.getBunchOfStrings().clear(); r.getBunchOfStrings().clear();
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
@ -165,23 +142,21 @@ public class CustomSQLTest extends LegacyTestCase {
} }
Person p = new Person(); Person p = new Person();
p.setName("Max"); p.setName("Max");
p.setLastName("Andersen"); p.setLastName("Andersen");
p.setNationalID("110974XYZ<EFBFBD>"); p.setNationalID("110974XYZ<EFBFBD>");
p.setAddress("P. P. Street 8"); p.setAddress("P. P. Street 8");
Session s = openSession(); Session s = openSession();
s.beginTransaction();
s.save(p); s.save(p);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
sessionFactory().evict(Person.class); sessionFactory().getCache().evictEntityRegion( Person.class );
s = openSession();
s = openSession();
s.beginTransaction();
Person p2 = (Person) s.get(Person.class, p.getId()); Person p2 = (Person) s.get(Person.class, p.getId());
assertNotSame(p, p2); assertNotSame(p, p2);
assertEquals(p2.getId(),p.getId()); assertEquals(p2.getId(),p.getId());
@ -191,11 +166,11 @@ public class CustomSQLTest extends LegacyTestCase {
List list = s.createQuery( "select p from Party as p" ).list(); List list = s.createQuery( "select p from Party as p" ).list();
assertTrue(list.size() == 1); assertTrue(list.size() == 1);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
list = s.createQuery( "select p from Person as p where p.address = 'L<>rkev<65>nget 1'" ).list(); list = s.createQuery( "select p from Person as p where p.address = 'L<>rkev<65>nget 1'" ).list();
assertTrue(list.size() == 0); assertTrue(list.size() == 0);
p.setAddress("L<EFBFBD>rkev<EFBFBD>nget 1"); p.setAddress("L<EFBFBD>rkev<EFBFBD>nget 1");
@ -209,7 +184,7 @@ public class CustomSQLTest extends LegacyTestCase {
list = s.createQuery( "select p from Person as p" ).list(); list = s.createQuery( "select p from Person as p" ).list();
assertTrue(list.size() == 0); assertTrue(list.size() == 0);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
} }

View File

@ -25,6 +25,7 @@ package org.hibernate.test.legacy;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Time; import java.sql.Time;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -75,6 +76,8 @@ import org.hibernate.dialect.TimesTenDialect;
import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.internal.util.SerializationHelper; import org.hibernate.internal.util.SerializationHelper;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jdbc.AbstractWork;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
@ -2094,10 +2097,16 @@ public class FooBarTest extends LegacyTestCase {
assertTrue( s.createFilter( baz.getFooArray(), "" ).list().size() == 1 ); assertTrue( s.createFilter( baz.getFooArray(), "" ).list().size() == 1 );
//assertTrue( s.delete("from java.lang.Object o")==9 ); //assertTrue( s.delete("from java.lang.Object o")==9 );
doDelete( s, "from Foo foo" ); doDelete( s, "from Foo foo" );
String bazid = baz.getCode(); final String bazid = baz.getCode();
s.delete( baz ); s.delete( baz );
int rows=s.connection().createStatement().executeUpdate( int rows = s.doReturningWork(
"delete from FOO_ARRAY where id_='" + bazid + "' and i>=8" new AbstractReturningWork<Integer>() {
@Override
public Integer execute(Connection connection) throws SQLException {
return connection.createStatement()
.executeUpdate( "delete from FOO_ARRAY where id_='" + bazid + "' and i>=8" );
}
}
); );
assertTrue( rows == 1 ); assertTrue( rows == 1 );
s.getTransaction().commit(); s.getTransaction().commit();
@ -2463,6 +2472,7 @@ public class FooBarTest extends LegacyTestCase {
} }
@Test @Test
@SuppressWarnings( {"UnnecessaryBoxing", "unchecked"})
public void testPersistCollections() throws Exception { public void testPersistCollections() throws Exception {
Session s = openSession(); Session s = openSession();
Transaction txn = s.beginTransaction(); Transaction txn = s.beginTransaction();
@ -2486,7 +2496,7 @@ public class FooBarTest extends LegacyTestCase {
s = openSession(); s = openSession();
txn = s.beginTransaction(); txn = s.beginTransaction();
assertTrue( ( (Long) s.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==1 ); assertEquals( 1L, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
baz = (Baz) ( (Object[]) s.createQuery( "select baz, baz from Baz baz" ).list().get(0) )[1]; baz = (Baz) ( (Object[]) s.createQuery( "select baz, baz from Baz baz" ).list().get(0) )[1];
assertTrue( baz.getCascadingBars().size()==1 ); assertTrue( baz.getCascadingBars().size()==1 );
//System.out.println( s.print(baz) ); //System.out.println( s.print(baz) );
@ -2525,7 +2535,7 @@ public class FooBarTest extends LegacyTestCase {
s = openSession(); s = openSession();
txn = s.beginTransaction(); txn = s.beginTransaction();
assertTrue( ( (Long) s.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==1 ); assertEquals( 1, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0);
assertTrue( "collection of custom types - added element", baz.getCustoms().size()==4 && baz.getCustoms().get(0)!=null ); assertTrue( "collection of custom types - added element", baz.getCustoms().size()==4 && baz.getCustoms().get(0)!=null );
assertTrue ( "component of component in collection", baz.getComponents()[1].getSubcomponent()!=null ); assertTrue ( "component of component in collection", baz.getComponents()[1].getSubcomponent()!=null );
@ -2557,7 +2567,7 @@ public class FooBarTest extends LegacyTestCase {
s = openSession(); s = openSession();
txn = s.beginTransaction(); txn = s.beginTransaction();
assertTrue( ( (Long) s.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==1 ); assertEquals( 1, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
baz = (Baz) s.load(Baz.class, baz.getCode()); baz = (Baz) s.load(Baz.class, baz.getCode());
assertTrue( baz.getCascadingBars().size()==1 ); assertTrue( baz.getCascadingBars().size()==1 );
Bar bar = new Bar(); Bar bar = new Bar();
@ -2592,7 +2602,7 @@ public class FooBarTest extends LegacyTestCase {
Session s2 = openSession(); Session s2 = openSession();
Transaction txn2 = s2.beginTransaction(); Transaction txn2 = s2.beginTransaction();
assertTrue( ( (Long) s2.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==3 ); assertEquals( 3, ((Long) s2.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
Baz baz2 = (Baz) s2.createQuery( "select baz from Baz baz order by baz" ).list().get(0); Baz baz2 = (Baz) s2.createQuery( "select baz from Baz baz order by baz" ).list().get(0);
Object o = baz2.getFooComponentToFoo().get( new FooComponent("name", 123, null, null) ); Object o = baz2.getFooComponentToFoo().get( new FooComponent("name", 123, null, null) );
assertTrue( assertTrue(
@ -2636,7 +2646,7 @@ public class FooBarTest extends LegacyTestCase {
s = openSession(); s = openSession();
txn = s.beginTransaction(); txn = s.beginTransaction();
assertTrue( ( (Long) s.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==3 ); assertEquals( 3, ((Long) s.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0); baz = (Baz) s.createQuery( "select baz from Baz baz order by baz" ).list().get(0);
assertTrue( baz.getTopGlarchez().size()==2 ); assertTrue( baz.getTopGlarchez().size()==2 );
assertTrue( baz.getCascadingBars().size()==1 ); assertTrue( baz.getCascadingBars().size()==1 );
@ -2647,11 +2657,19 @@ public class FooBarTest extends LegacyTestCase {
txn2 = s2.beginTransaction(); txn2 = s2.beginTransaction();
baz = (Baz) s2.load(Baz.class, baz.getCode()); baz = (Baz) s2.load(Baz.class, baz.getCode());
assertTrue( ( (Long) s2.createQuery( "select count(*) from Bar" ).iterate().next() ).longValue()==3 ); assertEquals( 3, ((Long) s2.createQuery( "select count(*) from Bar" ).iterate().next()).longValue() );
s2.delete(baz); s2.delete(baz);
s2.delete( baz.getTopGlarchez().get( new Character('G') ) ); s2.delete( baz.getTopGlarchez().get( Character.valueOf('G') ) );
s2.delete( baz.getTopGlarchez().get( new Character('H') ) ); s2.delete( baz.getTopGlarchez().get( Character.valueOf('H') ) );
int rows = s2.connection().createStatement().executeUpdate("update " + getDialect().openQuote() + "glarchez" + getDialect().closeQuote() + " set baz_map_id=null where baz_map_index='a'"); int rows = s2.doReturningWork(
new AbstractReturningWork<Integer>() {
@Override
public Integer execute(Connection connection) throws SQLException {
final String sql = "update " + getDialect().openQuote() + "glarchez" + getDialect().closeQuote() + " set baz_map_id=null where baz_map_index='a'";
return connection.createStatement().executeUpdate( sql );
}
}
);
assertTrue(rows==1); assertTrue(rows==1);
assertEquals( 2, doDelete( s2, "from Bar bar" ) ); assertEquals( 2, doDelete( s2, "from Bar bar" ) );
FooProxy[] arr = baz.getFooArray(); FooProxy[] arr = baz.getFooArray();
@ -2735,6 +2753,7 @@ public class FooBarTest extends LegacyTestCase {
} }
@Test @Test
@SuppressWarnings( {"unchecked"})
public void testUpdateCollections() throws Exception { public void testUpdateCollections() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction(); s.beginTransaction();
@ -2892,6 +2911,7 @@ public class FooBarTest extends LegacyTestCase {
} }
@Test @Test
@SuppressWarnings( {"unchecked"})
public void testCollectionOfSelf() throws Exception { public void testCollectionOfSelf() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction(); s.beginTransaction();
@ -2913,9 +2933,8 @@ public class FooBarTest extends LegacyTestCase {
s.load( bar, bar.getKey() ); s.load( bar, bar.getKey() );
assertTrue( "collection contains self", bar.getAbstracts().size() == 2 && bar.getAbstracts().contains( bar ) ); assertTrue( "collection contains self", bar.getAbstracts().size() == 2 && bar.getAbstracts().contains( bar ) );
assertTrue( "association to self", bar.getFoo()==bar ); assertTrue( "association to self", bar.getFoo()==bar );
Iterator iter = bar.getAbstracts().iterator(); for ( Object o : bar.getAbstracts() ) {
while ( iter.hasNext() ) { s.delete( o );
s.delete( iter.next() );
} }
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();
@ -3242,6 +3261,7 @@ public class FooBarTest extends LegacyTestCase {
@Test @Test
public void testVersionedCollections() throws Exception { public void testVersionedCollections() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
GlarchProxy g = new Glarch(); GlarchProxy g = new Glarch();
s.save(g); s.save(g);
g.setProxyArray( new GlarchProxy[] { g } ); g.setProxyArray( new GlarchProxy[] { g } );
@ -3250,66 +3270,66 @@ public class FooBarTest extends LegacyTestCase {
list.add("foo"); list.add("foo");
g.setStrings(list); g.setStrings(list);
HashSet set = new HashSet(); HashSet set = new HashSet();
set.add(g); set.add( g );
g.setProxySet(set); g.setProxySet( set );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( g.getStrings().size()==1 ); assertTrue( g.getStrings().size()==1 );
assertTrue( g.getProxyArray().length==1 ); assertTrue( g.getProxyArray().length==1 );
assertTrue( g.getProxySet().size()==1 ); assertTrue( g.getProxySet().size()==1 );
assertTrue( "versioned collection before", g.getVersion()==1 ); assertTrue( "versioned collection before", g.getVersion() == 1 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( g.getStrings().get(0).equals("foo") ); assertTrue( g.getStrings().get(0).equals("foo") );
assertTrue( g.getProxyArray()[0]==g ); assertTrue( g.getProxyArray()[0]==g );
assertTrue( g.getProxySet().iterator().next()==g ); assertTrue( g.getProxySet().iterator().next()==g );
assertTrue( "versioned collection before", g.getVersion()==1 ); assertTrue( "versioned collection before", g.getVersion() == 1 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( "versioned collection before", g.getVersion()==1 ); assertTrue( "versioned collection before", g.getVersion() == 1 );
g.getStrings().add("bar"); g.getStrings().add( "bar" );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( "versioned collection after", g.getVersion()==2 ); assertTrue( "versioned collection after", g.getVersion()==2 );
assertTrue( "versioned collection after", g.getStrings().size()==2 ); assertTrue( "versioned collection after", g.getStrings().size() == 2 );
g.setProxyArray(null); g.setProxyArray( null );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( "versioned collection after", g.getVersion()==3 ); assertTrue( "versioned collection after", g.getVersion()==3 );
assertTrue( "versioned collection after", g.getProxyArray().length==0 ); assertTrue( "versioned collection after", g.getProxyArray().length == 0 );
g.setFooComponents( new ArrayList() ); g.setFooComponents( new ArrayList() );
g.setProxyArray(null); g.setProxyArray( null );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
g = (GlarchProxy) s.load(Glarch.class, gid); g = (GlarchProxy) s.load(Glarch.class, gid);
assertTrue( "versioned collection after", g.getVersion()==4 ); assertTrue( "versioned collection after", g.getVersion()==4 );
s.delete(g); s.delete(g);
s.flush(); s.flush();
assertTrue( s.createQuery( "from java.lang.Object" ).list().size()==0 ); assertTrue( s.createQuery( "from java.lang.Object" ).list().size()==0 );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@ -4148,9 +4168,18 @@ public class FooBarTest extends LegacyTestCase {
assertEquals( assertEquals(
"cached object identity", "cached object identity",
im, im,
s.createQuery( "from Immutable im where im = ?" ).setParameter( 0, im, Hibernate.entity(Immutable.class) ).uniqueResult() s.createQuery( "from Immutable im where im = ?" ).setParameter(
0, im, Hibernate.entity( Immutable.class )
).uniqueResult()
);
s.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
connection.createStatement().executeUpdate("delete from immut");
}
}
); );
s.connection().createStatement().executeUpdate("delete from immut");
s.getTransaction().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@ -4187,9 +4216,17 @@ public class FooBarTest extends LegacyTestCase {
Session s = openSession(); Session s = openSession();
s.beginTransaction(); s.beginTransaction();
Foo foo = new Foo(); Foo foo = new Foo();
s.save(foo); s.save( foo );
s.flush(); s.flush();
s.connection().createStatement().executeUpdate( "update " + getDialect().openQuote() + "foos" + getDialect().closeQuote() + " set long_ = -3" ); s.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
final String sql = "update " + getDialect().openQuote() + "foos" + getDialect().closeQuote() + " set long_ = -3";
connection.createStatement().executeUpdate( sql );
}
}
);
s.refresh(foo); s.refresh(foo);
assertTrue( foo.getLong().longValue() == -3l ); assertTrue( foo.getLong().longValue() == -3l );
assertTrue( s.getCurrentLockMode(foo)==LockMode.READ ); assertTrue( s.getCurrentLockMode(foo)==LockMode.READ );
@ -4344,7 +4381,7 @@ public class FooBarTest extends LegacyTestCase {
@Test @Test
public void testUserProvidedConnection() throws Exception { public void testUserProvidedConnection() throws Exception {
ConnectionProvider dcp = ConnectionProviderBuilder.buildConnectionProvider(); ConnectionProvider dcp = ConnectionProviderBuilder.buildConnectionProvider();
Session s = sessionFactory().openSession( dcp.getConnection() ); Session s = sessionFactory().withOptions().connection( dcp.getConnection() ).openSession();
Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction();
s.createQuery( "from Fo" ).list(); s.createQuery( "from Fo" ).list();
tx.commit(); tx.commit();

View File

@ -862,10 +862,11 @@ public class FumTest extends LegacyTestCase {
s.close(); s.close();
s = sessionFactory().openSession(); s = sessionFactory().openSession();
s.beginTransaction();
s.setFlushMode(FlushMode.MANUAL); s.setFlushMode(FlushMode.MANUAL);
fum = (Fum) s.load( Fum.class, fum.getId() ); fum = (Fum) s.load( Fum.class, fum.getId() );
assertTrue("the Fum.friends is not empty", fum.getFriends() == null || fum.getFriends().size() == 0); assertTrue("the Fum.friends is not empty", fum.getFriends() == null || fum.getFriends().size() == 0);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }

View File

@ -53,6 +53,7 @@ public class MapTest extends LegacyTestCase {
@Test @Test
public void testMap() throws Exception { public void testMap() throws Exception {
Session s = openSession().getSession(EntityMode.MAP); Session s = openSession().getSession(EntityMode.MAP);
s.beginTransaction();
Map map = new HashMap(); Map map = new HashMap();
map.put("$type$", "TestMap"); map.put("$type$", "TestMap");
map.put("name", "foo"); map.put("name", "foo");
@ -62,21 +63,22 @@ public class MapTest extends LegacyTestCase {
cmp.put( "b", new Float(1.0) ); cmp.put( "b", new Float(1.0) );
map.put("cmp", cmp); map.put("cmp", cmp);
s.save(map); s.save(map);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession().getSession(EntityMode.MAP); s = openSession().getSession(EntityMode.MAP);
s.beginTransaction();
map = (Map) s.get( "TestMap", (Serializable) map.get("id") ); map = (Map) s.get( "TestMap", (Serializable) map.get("id") );
assertTrue( map!=null && "foo".equals( map.get("name") ) ); assertTrue( map!=null && "foo".equals( map.get("name") ) );
assertTrue( map.get("$type$").equals("TestMap") ); assertTrue( map.get("$type$").equals("TestMap") );
int size = s.createCriteria("TestMap").add( Example.create(map) ).list().size(); int size = s.createCriteria("TestMap").add( Example.create(map) ).list().size();
assertTrue(size==1); assertTrue(size==1);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession().getSession(EntityMode.MAP); s = openSession().getSession(EntityMode.MAP);
s.beginTransaction();
List list = s.createQuery("from TestMap").list(); List list = s.createQuery("from TestMap").list();
map = (Map) list.get(0); map = (Map) list.get(0);
assertTrue( "foo".equals( map.get("name") ) ); assertTrue( "foo".equals( map.get("name") ) );
@ -88,11 +90,11 @@ public class MapTest extends LegacyTestCase {
map.put("parent", map); map.put("parent", map);
List bag = (List) map.get("children"); List bag = (List) map.get("children");
bag.add(map); bag.add(map);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
list = s.createQuery("from TestMap tm where tm.address = 'bar'").list(); list = s.createQuery("from TestMap tm where tm.address = 'bar'").list();
map = (Map) list.get(0); map = (Map) list.get(0);
assertTrue( "foobar".equals( map.get("name") ) ); assertTrue( "foobar".equals( map.get("name") ) );
@ -110,8 +112,7 @@ public class MapTest extends LegacyTestCase {
assertTrue(size==1); assertTrue(size==1);
s.delete(map); s.delete(map);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -121,41 +122,41 @@ public class MapTest extends LegacyTestCase {
Map child = new HashMap(); Map child = new HashMap();
Map parent = new HashMap(); Map parent = new HashMap();
Session s = openSession(); Session s = openSession();
s.beginTransaction();
child.put("parent", parent); child.put("parent", parent);
child.put("$type$", "ChildMap"); child.put("$type$", "ChildMap");
parent.put("child", child); parent.put("child", child);
parent.put("$type$", "ParentMap"); parent.put("$type$", "ParentMap");
s.save(parent); s.save(parent);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Map cm = (Map) s.createQuery("from ChildMap cm where cm.parent is not null").uniqueResult(); Map cm = (Map) s.createQuery("from ChildMap cm where cm.parent is not null").uniqueResult();
s.delete(cm); s.delete(cm);
s.delete( cm.get("parent") ); s.delete( cm.get("parent") );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
child = new HashMap(); child = new HashMap();
parent = new HashMap(); parent = new HashMap();
s = openSession(); s = openSession();
s.beginTransaction();
child.put("parent", parent); child.put("parent", parent);
child.put("$type$", "ChildMap"); child.put("$type$", "ChildMap");
parent.put("child", child); parent.put("child", child);
parent.put("$type$", "ParentMap"); parent.put("$type$", "ParentMap");
s.save(child); s.save(child);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Map pm = (Map) s.createQuery("from ParentMap cm where cm.child is not null").uniqueResult(); Map pm = (Map) s.createQuery("from ParentMap cm where cm.child is not null").uniqueResult();
s.delete(pm); s.delete(pm);
s.delete( pm.get("child") ); s.delete( pm.get("child") );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -163,6 +164,7 @@ public class MapTest extends LegacyTestCase {
@Test @Test
public void testOneToOnePropertyRef() throws Exception { public void testOneToOnePropertyRef() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
s.createQuery("from Commento c where c.marelo.mlmag = 0").list(); s.createQuery("from Commento c where c.marelo.mlmag = 0").list();
s.createQuery("from Commento c where c.marelo.commento.mcompr is null").list(); s.createQuery("from Commento c where c.marelo.commento.mcompr is null").list();
s.createQuery("from Commento c where c.marelo.mlink = 0").list(); s.createQuery("from Commento c where c.marelo.mlink = 0").list();
@ -172,7 +174,7 @@ public class MapTest extends LegacyTestCase {
s.createQuery("from Commento c where c.marelo.commento.mclink = c.mclink").list(); s.createQuery("from Commento c where c.marelo.commento.mclink = c.mclink").list();
s.createQuery("from Marelo m where m.commento.id > 0").list(); s.createQuery("from Marelo m where m.commento.id > 0").list();
s.createQuery("from Marelo m where m.commento.marelo.commento.marelo.mlmag is not null").list(); s.createQuery("from Marelo m where m.commento.marelo.commento.marelo.mlmag is not null").list();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }

View File

@ -25,6 +25,7 @@ package org.hibernate.test.legacy;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet; import java.util.HashSet;
@ -43,6 +44,8 @@ import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MckoiDialect; import org.hibernate.dialect.MckoiDialect;
import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.SAPDBDialect; import org.hibernate.dialect.SAPDBDialect;
import org.hibernate.jdbc.AbstractWork;
import org.hibernate.jdbc.Work;
import org.hibernate.mapping.MetaAttribute; import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
@ -73,28 +76,29 @@ public class MasterDetailTest extends LegacyTestCase {
@Test @Test
public void testOuterJoin() throws Exception { public void testOuterJoin() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Eye e = new Eye(); Eye e = new Eye();
e.setName("Eye Eye"); e.setName("Eye Eye");
Jay jay = new Jay(e); Jay jay = new Jay(e);
e.setJay(jay); e.setJay( jay );
s.saveOrUpdate(e); s.saveOrUpdate( e );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
e = (Eye) s.createCriteria(Eye.class).uniqueResult(); e = (Eye) s.createCriteria(Eye.class).uniqueResult();
assertTrue( Hibernate.isInitialized( e.getJay() ) ); assertTrue( Hibernate.isInitialized( e.getJay() ) );
assertTrue( Hibernate.isInitialized( e.getJays() ) ); assertTrue( Hibernate.isInitialized( e.getJays() ) );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
jay = (Jay) s.createQuery("select new Jay(eye) from Eye eye").uniqueResult(); jay = (Jay) s.createQuery("select new Jay(eye) from Eye eye").uniqueResult();
assertTrue( "Eye Eye".equals( jay.getEye().getName() ) ); assertTrue( "Eye Eye".equals( jay.getEye().getName() ) );
s.delete( jay.getEye() ); s.delete( jay.getEye() );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -108,6 +112,7 @@ public class MasterDetailTest extends LegacyTestCase {
} }
@Test @Test
@SuppressWarnings( {"unchecked"})
public void testCopy() throws Exception { public void testCopy() throws Exception {
Category catWA = new Category(); Category catWA = new Category();
catWA.setName("HSQL workaround"); catWA.setName("HSQL workaround");
@ -119,11 +124,12 @@ public class MasterDetailTest extends LegacyTestCase {
subCatBaz.setName("baz"); subCatBaz.setName("baz");
cat.getSubcategories().add(subCatBar); cat.getSubcategories().add(subCatBar);
cat.getSubcategories().add(subCatBaz); cat.getSubcategories().add(subCatBaz);
Session s = openSession(); Session s = openSession();
s.save(catWA); s.beginTransaction();
s.save(cat); s.save( catWA );
s.flush(); s.save( cat );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
cat.setName("new foo"); cat.setName("new foo");
@ -137,9 +143,9 @@ public class MasterDetailTest extends LegacyTestCase {
newCat.getSubcategories().add(newSubCat); newCat.getSubcategories().add(newSubCat);
s = openSession(); s = openSession();
s.beginTransaction();
Category copiedCat = (Category) s.merge( cat ); Category copiedCat = (Category) s.merge( cat );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
assertFalse( copiedCat==cat ); assertFalse( copiedCat==cat );
@ -156,11 +162,11 @@ public class MasterDetailTest extends LegacyTestCase {
cat.setName("new new foo"); cat.setName("new new foo");
s = openSession(); s = openSession();
s.beginTransaction();
s.delete(cat); s.delete(cat);
s.delete(subCatBaz); s.delete( subCatBaz );
s.delete(catWA); s.delete( catWA );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -491,6 +497,7 @@ public class MasterDetailTest extends LegacyTestCase {
@Test @Test
public void testIncomingOutgoing() throws Exception { public void testIncomingOutgoing() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Master master1 = new Master(); Master master1 = new Master();
Master master2 = new Master(); Master master2 = new Master();
Master master3 = new Master(); Master master3 = new Master();
@ -502,12 +509,16 @@ public class MasterDetailTest extends LegacyTestCase {
master1.addIncoming(master3); master1.addIncoming(master3);
master3.addOutgoing(master1); master3.addOutgoing(master1);
Serializable m1id = s.getIdentifier(master1); Serializable m1id = s.getIdentifier(master1);
assertTrue( s.createFilter( master1.getIncoming(), "where this.id > 0 and this.name is not null" ).list().size()==2 ); assertTrue(
s.flush(); s.createFilter( master1.getIncoming(), "where this.id > 0 and this.name is not null" )
s.connection().commit(); .list()
.size() == 2
);
s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
master1 = (Master) s.load(Master.class, m1id); master1 = (Master) s.load(Master.class, m1id);
Iterator iter = master1.getIncoming().iterator(); Iterator iter = master1.getIncoming().iterator();
int i=0; int i=0;
@ -518,16 +529,16 @@ public class MasterDetailTest extends LegacyTestCase {
s.delete(m); s.delete(m);
i++; i++;
} }
assertTrue( "incoming-outgoing", i==2 ); assertTrue( "incoming-outgoing", i == 2 );
s.delete(master1); s.delete( master1 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testCascading() throws Exception { public void testCascading() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Detail d1 = new Detail(); Detail d1 = new Detail();
Detail d2 = new Detail(); Detail d2 = new Detail();
d2.setI(22); d2.setI(22);
@ -539,55 +550,57 @@ public class MasterDetailTest extends LegacyTestCase {
m.getMoreDetails().add(d1); m.getMoreDetails().add(d1);
m.getMoreDetails().add(d2); m.getMoreDetails().add(d2);
Serializable mid = s.save(m); Serializable mid = s.save(m);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
m = (Master) s.load(Master.class, mid); m = (Master) s.load(Master.class, mid);
assertTrue( "cascade save", m.getMoreDetails().size()==2 ); assertTrue( "cascade save", m.getMoreDetails().size()==2 );
assertTrue( "cascade save", ( (Detail) m.getMoreDetails().iterator().next() ).getMaster().getDetails().size()==2 ); assertTrue( "cascade save", ( (Detail) m.getMoreDetails().iterator().next() ).getMaster().getDetails().size()==2 );
s.delete( m );
s.delete(m); s.delete( s.load( Master.class, m0id ) );
s.delete( s.load(Master.class, m0id) ); s.getTransaction().commit();
s.flush();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testNamedQuery() throws Exception { public void testNamedQuery() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Query q = s.getNamedQuery("all_details"); Query q = s.getNamedQuery("all_details");
q.list(); q.list();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@Test @Test
public void testUpdateLazyCollections() throws Exception { public void testUpdateLazyCollections() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Master m = new Master(); Master m = new Master();
s.save( m ); s.save( m );
Detail d1 = new Detail(); Detail d1 = new Detail();
Detail d2 = new Detail(); Detail d2 = new Detail();
d2.setX(14); d2.setX( 14 );
d1.setMaster(m); d1.setMaster( m );
d2.setMaster(m); d2.setMaster( m );
s.save(d1); s.save( d1 );
s.save(d2); s.save( d2 );
m.addDetail(d1); m.addDetail( d1 );
m.addDetail(d2); m.addDetail( d2 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
m = (Master) s.load( Master.class, m.getId() ); m = (Master) s.load( Master.class, m.getId() );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
m.setName("New Name"); m.setName("New Name");
s = openSession(); s = openSession();
s.beginTransaction();
s.update( m ); s.update( m );
Iterator iter = m.getDetails().iterator(); Iterator iter = m.getDetails().iterator();
int i=0; int i=0;
@ -598,9 +611,8 @@ public class MasterDetailTest extends LegacyTestCase {
assertTrue(i==2); assertTrue(i==2);
iter = m.getDetails().iterator(); iter = m.getDetails().iterator();
while ( iter.hasNext() ) s.delete( iter.next() ); while ( iter.hasNext() ) s.delete( iter.next() );
s.delete(m); s.delete( m );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -637,22 +649,23 @@ public class MasterDetailTest extends LegacyTestCase {
@Test @Test
public void testMixNativeAssigned() throws Exception { public void testMixNativeAssigned() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
c.setName("NAME"); c.setName("NAME");
Assignable assn = new Assignable(); Assignable assn = new Assignable();
assn.setId("i.d."); assn.setId("i.d.");
List l = new ArrayList(); List l = new ArrayList();
l.add(c); l.add( c );
assn.setCategories(l); assn.setCategories( l );
c.setAssignable(assn); c.setAssignable( assn );
s.save(assn); s.save( assn );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.delete(assn); s.beginTransaction();
s.flush(); s.delete( assn );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@ -785,6 +798,7 @@ public class MasterDetailTest extends LegacyTestCase {
@Test @Test
public void testCategories() throws Exception { public void testCategories() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
c.setName(Category.ROOT_CATEGORY); c.setName(Category.ROOT_CATEGORY);
Category c1 = new Category(); Category c1 = new Category();
@ -792,38 +806,40 @@ public class MasterDetailTest extends LegacyTestCase {
Category c3 = new Category(); Category c3 = new Category();
c.getSubcategories().add(c1); c.getSubcategories().add(c1);
c.getSubcategories().add(c2); c.getSubcategories().add(c2);
c2.getSubcategories().add(null); c2.getSubcategories().add( null );
c2.getSubcategories().add(c3); c2.getSubcategories().add( c3 );
s.save(c); s.save( c );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
Transaction tx = s.beginTransaction(); s.beginTransaction();
s.lock(c, LockMode.UPGRADE); s.lock(c, LockMode.UPGRADE);
Category loaded = (Category) s.load( Category.class, new Long( c3.getId() ) ); Category loaded = (Category) s.load( Category.class, new Long( c3.getId() ) );
assertTrue( s.contains(c3) ); assertTrue( s.contains(c3) );
assertTrue(loaded==c3); assertTrue(loaded==c3);
assertTrue( s.getCurrentLockMode(c3)==LockMode.NONE ); assertTrue( s.getCurrentLockMode(c3)==LockMode.NONE );
assertTrue( s.getCurrentLockMode(c)==LockMode.UPGRADE ); assertTrue( s.getCurrentLockMode( c ) == LockMode.UPGRADE );
s.flush(); s.flush();
tx.commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
loaded = (Category) s.load( Category.class, new Long( c.getId() ) ); loaded = (Category) s.load( Category.class, new Long( c.getId() ) );
assertFalse( Hibernate.isInitialized( loaded.getSubcategories() ) ); assertFalse( Hibernate.isInitialized( loaded.getSubcategories() ) );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
s.lock(loaded, LockMode.NONE); s.lock(loaded, LockMode.NONE);
assertTrue( loaded.getSubcategories().size()==2 ); assertTrue( loaded.getSubcategories().size()==2 );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
c = (Category) s.load( Category.class, new Long( c.getId() ) ); c = (Category) s.load( Category.class, new Long( c.getId() ) );
System.out.println( c.getSubcategories() ); System.out.println( c.getSubcategories() );
assertTrue( c.getSubcategories().get(0)!=null && c.getSubcategories().get(1)!=null ); assertTrue( c.getSubcategories().get(0)!=null && c.getSubcategories().get(1)!=null );
@ -834,38 +850,39 @@ public class MasterDetailTest extends LegacyTestCase {
s.createQuery( "from Category c where c.name = org.hibernate.test.legacy.Category.ROOT_CATEGORY" ) s.createQuery( "from Category c where c.name = org.hibernate.test.legacy.Category.ROOT_CATEGORY" )
.iterate().hasNext() .iterate().hasNext()
); );
s.delete(c); s.delete( c );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testCollectionRefresh() throws Exception { public void testCollectionRefresh() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
List list = new ArrayList(); List list = new ArrayList();
c.setSubcategories(list); c.setSubcategories(list);
list.add( new Category() ); list.add( new Category() );
c.setName("root"); c.setName("root");
Serializable id = s.save(c); Serializable id = s.save(c);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
c = (Category) s.load(Category.class, id); c = (Category) s.load(Category.class, id);
s.refresh(c); s.refresh( c );
s.flush(); s.flush();
assertTrue( c.getSubcategories().size()==1 ); assertTrue( c.getSubcategories().size() == 1 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
c = (Category) s.load(Category.class, id); c = (Category) s.load(Category.class, id);
assertTrue( c.getSubcategories().size()==1 ); assertTrue( c.getSubcategories().size() == 1 );
s.delete(c); s.delete( c );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -894,61 +911,69 @@ public class MasterDetailTest extends LegacyTestCase {
return; return;
} }
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
List list = new ArrayList(); List list = new ArrayList();
c.setSubcategories(list); c.setSubcategories(list);
list.add( new Category() ); list.add( new Category() );
c.setName("root"); c.setName("root");
Serializable id = s.save(c); Serializable id = s.save(c);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
c = (Category) s.load(Category.class, id); c = (Category) s.load(Category.class, id);
c.getSubcategories().size(); //force load and cache c.getSubcategories().size(); //force load and cache
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
if ( (getDialect() instanceof MySQLDialect) ) { if ( (getDialect() instanceof MySQLDialect) ) {
s.connection().setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); s.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
connection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED );
}
}
);
} }
s.beginTransaction();
c = (Category) s.load(Category.class, id); c = (Category) s.load(Category.class, id);
c.getSubcategories().size(); //force load c.getSubcategories().size(); //force load
Session ss = openSession(); Session ss = openSession();
ss.beginTransaction();
Category c2 = (Category) ss.load(Category.class, id); Category c2 = (Category) ss.load(Category.class, id);
ss.delete( c2.getSubcategories().get(0) ); ss.delete( c2.getSubcategories().get(0) );
c2.getSubcategories().clear(); c2.getSubcategories().clear();
ss.flush(); ss.getTransaction().commit();
ss.connection().commit();
ss.close(); ss.close();
s.refresh(c); s.refresh(c);
assertTrue( c.getSubcategories().size()==0 ); assertTrue( c.getSubcategories().size()==0 );
ss = openSession(); ss = openSession();
ss.beginTransaction();
c2 = (Category) ss.load(Category.class, id); c2 = (Category) ss.load(Category.class, id);
c2.getSubcategories().add( new Category() ); c2.getSubcategories().add( new Category() );
c2.getSubcategories().add( new Category() ); c2.getSubcategories().add( new Category() );
ss.flush(); ss.getTransaction().commit();
ss.connection().commit();
ss.close(); ss.close();
s.refresh(c); s.refresh(c);
assertEquals( 2, c.getSubcategories().size() ); assertEquals( 2, c.getSubcategories().size() );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
c = (Category) s.load(Category.class, id); c = (Category) s.load(Category.class, id);
assertEquals( 2, c.getSubcategories().size() ); assertEquals( 2, c.getSubcategories().size() );
s.delete(c); s.delete(c);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -990,21 +1015,23 @@ public class MasterDetailTest extends LegacyTestCase {
@Test @Test
public void testInterface() throws Exception { public void testInterface() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Serializable id = s.save( new BasicNameable() ); Serializable id = s.save( new BasicNameable() );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Nameable n = (Nameable) s.load(Nameable.class, id); Nameable n = (Nameable) s.load(Nameable.class, id);
s.delete(n); s.delete(n);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testNoUpdateManyToOne() throws Exception { public void testNoUpdateManyToOne() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
W w1 = new W(); W w1 = new W();
W w2 = new W(); W w2 = new W();
Z z = new Z(); Z z = new Z();
@ -1012,25 +1039,25 @@ public class MasterDetailTest extends LegacyTestCase {
s.save(z); s.save(z);
s.flush(); s.flush();
z.setW(w2); z.setW(w2);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
s.update(z); s.update(z);
s.flush(); s.flush();
s.delete(z); s.delete(z);
for ( Object entity : s.createQuery( "from W" ).list() ) { for ( Object entity : s.createQuery( "from W" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@Test @Test
public void testQueuedBagAdds() throws Exception { public void testQueuedBagAdds() throws Exception {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Assignable a = new Assignable(); Assignable a = new Assignable();
a.setId("foo"); a.setId("foo");
a.setCategories( new ArrayList() ); a.setCategories( new ArrayList() );
@ -1038,26 +1065,26 @@ public class MasterDetailTest extends LegacyTestCase {
c.setAssignable(a); c.setAssignable(a);
a.getCategories().add(c); a.getCategories().add(c);
s.save(a); s.save(a);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
sessionFactory().evictCollection("org.hibernate.test.legacy.Assignable.categories"); sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" );
s = openSession(); s = openSession();
s.beginTransaction();
a = (Assignable) s.get(Assignable.class, "foo"); a = (Assignable) s.get(Assignable.class, "foo");
c = new Category(); c = new Category();
c.setAssignable(a); c.setAssignable(a);
a.getCategories().add(c); a.getCategories().add(c);
assertFalse( Hibernate.isInitialized( a.getCategories() ) ); assertFalse( Hibernate.isInitialized( a.getCategories() ) );
assertTrue( a.getCategories().size()==2 ); assertTrue( a.getCategories().size()==2 );
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
sessionFactory().evictCollection("org.hibernate.test.legacy.Assignable.categories"); sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" );
s = openSession(); s = openSession();
s.beginTransaction();
a = (Assignable) s.get(Assignable.class, "foo"); a = (Assignable) s.get(Assignable.class, "foo");
c = new Category(); c = new Category();
c.setAssignable(a); c.setAssignable(a);
@ -1066,17 +1093,17 @@ public class MasterDetailTest extends LegacyTestCase {
s.flush(); s.flush();
assertFalse( Hibernate.isInitialized( a.getCategories() ) ); assertFalse( Hibernate.isInitialized( a.getCategories() ) );
assertTrue( a.getCategories().size()==3 ); assertTrue( a.getCategories().size()==3 );
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
sessionFactory().evictCollection("org.hibernate.test.legacy.Assignable.categories"); sessionFactory().getCache().evictCollectionRegion( "org.hibernate.test.legacy.Assignable.categories" );
s = openSession(); s = openSession();
s.beginTransaction();
a = (Assignable) s.get(Assignable.class, "foo"); a = (Assignable) s.get(Assignable.class, "foo");
assertTrue( a.getCategories().size()==3 ); assertTrue( a.getCategories().size()==3 );
s.delete(a); s.delete(a);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }

View File

@ -2,6 +2,8 @@
package org.hibernate.test.legacy; package org.hibernate.test.legacy;
import java.io.Serializable; import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashSet; import java.util.HashSet;
@ -16,6 +18,7 @@ import org.hibernate.Session;
import org.hibernate.Transaction; import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Restrictions;
import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.MySQLDialect;
import org.hibernate.jdbc.Work;
import org.junit.Test; import org.junit.Test;
@ -122,9 +125,16 @@ public class MultiTableTest extends LegacyTestCase {
s = openSession(); s = openSession();
s.beginTransaction(); s.beginTransaction();
s.connection().createStatement().executeQuery( s.doWork(
"select * from leafsubsubclass sm, nonleafsubclass m, rootclass s where sm.sid=m.sid and sm.sid=s.id1_ and sm.sid=1" new Work() {
).next(); @Override
public void execute(Connection connection) throws SQLException {
final String sql = "select * from leafsubsubclass sm, nonleafsubclass m, rootclass s " +
"where sm.sid=m.sid and sm.sid=s.id1_ and sm.sid=1";
connection.createStatement().executeQuery( sql ).next();
}
}
);
assertTrue( assertTrue(
s.createQuery( s.createQuery(
"select s from SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null" "select s from SubMulti as sm join sm.children as s where s.amount>-1 and s.name is null"

View File

@ -50,6 +50,7 @@ import org.hibernate.dialect.IngresDialect;
import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.MySQLDialect;
import org.hibernate.engine.EntityEntry; import org.hibernate.engine.EntityEntry;
import org.hibernate.impl.SessionImpl; import org.hibernate.impl.SessionImpl;
import org.hibernate.jdbc.AbstractWork;
import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxy;
import org.junit.Test; import org.junit.Test;
@ -1194,7 +1195,14 @@ public class ParentChildTest extends LegacyTestCase {
public void testLoadAfterNonExists() throws HibernateException, SQLException { public void testLoadAfterNonExists() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
if ( ( getDialect() instanceof MySQLDialect ) || ( getDialect() instanceof IngresDialect ) ) { if ( ( getDialect() instanceof MySQLDialect ) || ( getDialect() instanceof IngresDialect ) ) {
session.connection().setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED ); session.doWork(
new AbstractWork() {
@Override
public void execute(Connection connection) throws SQLException {
connection.setTransactionIsolation( Connection.TRANSACTION_READ_COMMITTED );
}
}
);
} }
session.getTransaction().begin(); session.getTransaction().begin();

View File

@ -555,6 +555,7 @@ public class SQLFunctionsTest extends LegacyTestCase {
return; return;
} }
Session s = openSession(); Session s = openSession();
s.beginTransaction();
Blobber b = new Blobber(); Blobber b = new Blobber();
b.setBlob( s.getLobHelper().createBlob( "foo/bar/baz".getBytes() ) ); b.setBlob( s.getLobHelper().createBlob( "foo/bar/baz".getBytes() ) );
b.setClob( s.getLobHelper().createClob("foo/bar/baz") ); b.setClob( s.getLobHelper().createClob("foo/bar/baz") );
@ -568,10 +569,11 @@ public class SQLFunctionsTest extends LegacyTestCase {
b.getClob().getSubString(2, 3); b.getClob().getSubString(2, 3);
//b.getClob().setString(2, "abc"); //b.getClob().setString(2, "abc");
s.flush(); s.flush();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
Blobber b2 = new Blobber(); Blobber b2 = new Blobber();
s.save(b2); s.save(b2);
@ -581,22 +583,24 @@ public class SQLFunctionsTest extends LegacyTestCase {
b.getClob().getSubString(1, 6); b.getClob().getSubString(1, 6);
//b.getClob().setString(1, "qwerty"); //b.getClob().setString(1, "qwerty");
s.flush(); s.flush();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
b.setClob( s.getLobHelper().createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb") ); b.setClob( s.getLobHelper().createClob("xcvfxvc xcvbx cvbx cvbx cvbxcvbxcvbxcvb") );
s.flush(); s.flush();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) ); b = (Blobber) s.load( Blobber.class, new Integer( b.getId() ) );
assertTrue( b.getClob().getSubString(1, 7).equals("xcvfxvc") ); assertTrue( b.getClob().getSubString(1, 7).equals("xcvfxvc") );
//b.getClob().setString(5, "1234567890"); //b.getClob().setString(5, "1234567890");
s.flush(); s.flush();
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }

View File

@ -63,6 +63,7 @@ public class SQLLoaderTest extends LegacyTestCase {
@Test @Test
public void testFindBySQLStar() throws HibernateException, SQLException { public void testFindBySQLStar() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from Assignable" ).list() ) { for ( Object entity : session.createQuery( "from Assignable" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -95,13 +96,14 @@ public class SQLLoaderTest extends LegacyTestCase {
session.createSQLQuery( "select {simple.*} from Simple {simple}" ).addEntity( "simple", Simple.class ).list(); session.createSQLQuery( "select {simple.*} from Simple {simple}" ).addEntity( "simple", Simple.class ).list();
session.createSQLQuery( "select {a.*} from TA {a}" ).addEntity( "a", A.class ).list(); session.createSQLQuery( "select {a.*} from TA {a}" ).addEntity( "a", A.class ).list();
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testFindBySQLProperties() throws HibernateException, SQLException { public void testFindBySQLProperties() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from Category" ).list() ) { for ( Object entity : session.createQuery( "from Category" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -144,13 +146,14 @@ public class SQLLoaderTest extends LegacyTestCase {
query.setParameterList("names", str); query.setParameterList("names", str);
query.uniqueResult(); query.uniqueResult();
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testFindBySQLAssociatedObjects() throws HibernateException, SQLException { public void testFindBySQLAssociatedObjects() throws HibernateException, SQLException {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
for ( Object entity : s.createQuery( "from Assignable" ).list() ) { for ( Object entity : s.createQuery( "from Assignable" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
@ -167,19 +170,22 @@ public class SQLLoaderTest extends LegacyTestCase {
assn.setCategories(l); assn.setCategories(l);
c.setAssignable(assn); c.setAssignable(assn);
s.save(assn); s.save(assn);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
List list = s.createSQLQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list(); List list = s.createSQLQuery( "select {category.*} from category {category}" ).addEntity( "category", Category.class ).list();
list.get(0); list.get(0);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
if ( getDialect() instanceof MySQLDialect ) return; if ( getDialect() instanceof MySQLDialect ) {
return;
}
s = openSession(); s = openSession();
s.beginTransaction();
Query query = s.getNamedQuery("namedsql"); Query query = s.getNamedQuery("namedsql");
assertNotNull(query); assertNotNull(query);
@ -191,8 +197,8 @@ public class SQLLoaderTest extends LegacyTestCase {
assertNotNull(values[1]); assertNotNull(values[1]);
assertTrue("wrong type: " + values[0].getClass(), values[0] instanceof Category); assertTrue("wrong type: " + values[0].getClass(), values[0] instanceof Category);
assertTrue("wrong type: " + values[1].getClass(), values[1] instanceof Assignable); assertTrue("wrong type: " + values[1].getClass(), values[1] instanceof Assignable);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@ -201,6 +207,7 @@ public class SQLLoaderTest extends LegacyTestCase {
@SkipForDialect( MySQLDialect.class ) @SkipForDialect( MySQLDialect.class )
public void testPropertyResultSQL() throws HibernateException, SQLException { public void testPropertyResultSQL() throws HibernateException, SQLException {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
for ( Object entity : s.createQuery( "from Assignable" ).list() ) { for ( Object entity : s.createQuery( "from Assignable" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
@ -217,20 +224,17 @@ public class SQLLoaderTest extends LegacyTestCase {
assn.setCategories(l); assn.setCategories(l);
c.setAssignable(assn); c.setAssignable(assn);
s.save(assn); s.save(assn);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Query query = s.getNamedQuery("nonaliasedsql"); Query query = s.getNamedQuery("nonaliasedsql");
assertNotNull(query); assertNotNull(query);
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull(list);
assertTrue(list.get(0) instanceof Category); assertTrue(list.get(0) instanceof Category);
s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -238,17 +242,18 @@ public class SQLLoaderTest extends LegacyTestCase {
@Test @Test
public void testFindBySQLMultipleObject() throws HibernateException, SQLException { public void testFindBySQLMultipleObject() throws HibernateException, SQLException {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
for ( Object entity : s.createQuery( "from Assignable" ).list() ) { for ( Object entity : s.createQuery( "from Assignable" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
for ( Object entity : s.createQuery( "from Category" ).list() ) { for ( Object entity : s.createQuery( "from Category" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
s.getTransaction().commit();
s.flush();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
c.setName("NAME"); c.setName("NAME");
Assignable assn = new Assignable(); Assignable assn = new Assignable();
@ -273,36 +278,40 @@ public class SQLLoaderTest extends LegacyTestCase {
assn = new Assignable(); assn = new Assignable();
assn.setId("i.d.3"); assn.setId("i.d.3");
s.save(assn); s.save(assn);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
if ( getDialect() instanceof MySQLDialect ) return; if ( getDialect() instanceof MySQLDialect ) {
return;
}
s = openSession(); s = openSession();
s.beginTransaction();
String sql = "select {category.*}, {assignable.*} from category {category}, \"assign-able\" {assignable}"; String sql = "select {category.*}, {assignable.*} from category {category}, \"assign-able\" {assignable}";
List list = s.createSQLQuery( sql ).addEntity( "category", Category.class ).addEntity( "assignable", Assignable.class ).list(); List list = s.createSQLQuery( sql ).addEntity( "category", Category.class ).addEntity( "assignable", Assignable.class ).list();
assertTrue(list.size() == 6); // crossproduct of 2 categories x 3 assignables assertTrue(list.size() == 6); // crossproduct of 2 categories x 3 assignables
assertTrue(list.get(0) instanceof Object[]); assertTrue(list.get(0) instanceof Object[]);
s.connection().commit(); s.getTransaction().commit();
s.close(); s.close();
} }
@Test @Test
public void testFindBySQLParameters() throws HibernateException, SQLException { public void testFindBySQLParameters() throws HibernateException, SQLException {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
for ( Object entity : s.createQuery( "from Assignable" ).list() ) { for ( Object entity : s.createQuery( "from Assignable" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
for ( Object entity : s.createQuery( "from Category" ).list() ) { for ( Object entity : s.createQuery( "from Category" ).list() ) {
s.delete( entity ); s.delete( entity );
} }
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Category c = new Category(); Category c = new Category();
c.setName("Good"); c.setName("Good");
Assignable assn = new Assignable(); Assignable assn = new Assignable();
@ -337,11 +346,11 @@ public class SQLLoaderTest extends LegacyTestCase {
assn = new Assignable(); assn = new Assignable();
assn.setId("i.d.3"); assn.setId("i.d.3");
s.save(assn); s.save(assn);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
Query basicParam = s.createSQLQuery( "select {category.*} from category {category} where {category}.name = 'Best'" ) Query basicParam = s.createSQLQuery( "select {category.*} from category {category} where {category}.name = 'Best'" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
List list = basicParam.list(); List list = basicParam.list();
@ -360,8 +369,7 @@ public class SQLLoaderTest extends LegacyTestCase {
namedParam.setString("secondCat", "Best"); namedParam.setString("secondCat", "Best");
list = namedParam.list(); list = namedParam.list();
assertEquals(2, list.size()); assertEquals(2, list.size());
s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
@ -369,6 +377,7 @@ public class SQLLoaderTest extends LegacyTestCase {
@SkipForDialect( { HSQLDialect.class, PostgreSQLDialect.class } ) @SkipForDialect( { HSQLDialect.class, PostgreSQLDialect.class } )
public void testEscapedJDBC() throws HibernateException, SQLException { public void testEscapedJDBC() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from A" ).list() ) { for ( Object entity : session.createQuery( "from A" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -381,9 +390,11 @@ public class SQLLoaderTest extends LegacyTestCase {
session.flush(); session.flush();
int count = session.createQuery("from A").list().size(); int count = session.createQuery("from A").list().size();
session.getTransaction().commit();
session.close(); session.close();
session = openSession(); session = openSession();
session.beginTransaction();
Query query; Query query;
if( getDialect() instanceof TimesTenDialect) { if( getDialect() instanceof TimesTenDialect) {
@ -400,13 +411,14 @@ public class SQLLoaderTest extends LegacyTestCase {
assertNotNull(list); assertNotNull(list);
assertEquals(1, list.size()); assertEquals(1, list.size());
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testDoubleAliasing() throws HibernateException, SQLException { public void testDoubleAliasing() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from A" ).list() ) { for ( Object entity : session.createQuery( "from A" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -419,10 +431,11 @@ public class SQLLoaderTest extends LegacyTestCase {
session.flush(); session.flush();
int count = session.createQuery("from A").list().size(); int count = session.createQuery("from A").list().size();
session.getTransaction().commit();
session.close(); session.close();
session = openSession(); session = openSession();
session.beginTransaction();
String sql = "select a.identifier_column as {a1.id}, " + String sql = "select a.identifier_column as {a1.id}, " +
" a.clazz_discriminata as {a1.class}, " + " a.clazz_discriminata as {a1.class}, " +
" a.count_ as {a1.count}, " + " a.count_ as {a1.count}, " +
@ -438,67 +451,63 @@ public class SQLLoaderTest extends LegacyTestCase {
assertNotNull(list); assertNotNull(list);
assertEquals(2, list.size()); assertEquals(2, list.size());
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testEmbeddedCompositeProperties() throws HibernateException, SQLException { public void testEmbeddedCompositeProperties() throws HibernateException, SQLException {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
Single s = new Single();
s.setId("my id");
s.setString("string 1");
session.save(s);
session.getTransaction().commit();
Single s = new Single(); session = openSession();
s.setId("my id"); session.beginTransaction();
s.setString("string 1");
session.save(s);
session.flush();
session.connection().commit();
session.clear(); SQLQuery query = session.createSQLQuery( "select {sing.*} from Single {sing}" ).addEntity( "sing", Single.class );
List list = query.list();
assertTrue(list.size()==1);
SQLQuery query = session.createSQLQuery( "select {sing.*} from Single {sing}" ).addEntity( "sing", Single.class ); session.clear();
List list = query.list(); query = session.createSQLQuery( "select {sing.*} from Single {sing} where sing.id = ?" ).addEntity( "sing", Single.class );
query.setString(0, "my id");
list = query.list();
assertTrue(list.size()==1);
assertTrue(list.size()==1); session.clear();
session.clear(); query = session.createSQLQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" )
query = session.createSQLQuery( "select {sing.*} from Single {sing} where sing.id = ?" ).addEntity( "sing", Single.class );
query.setString(0, "my id");
list = query.list();
assertTrue(list.size()==1);
session.clear();
query = session.createSQLQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" )
.addEntity( "sing", Single.class ); .addEntity( "sing", Single.class );
query.setString(0, "my id"); query.setString(0, "my id");
list = query.list(); list = query.list();
assertTrue(list.size()==1);
assertTrue(list.size()==1); session.clear();
session.clear(); query = session.createSQLQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" )
query = session.createSQLQuery( "select s.id as {sing.id}, s.string_ as {sing.string}, s.prop as {sing.prop} from Single s where s.id = ?" )
.addEntity( "sing", Single.class ); .addEntity( "sing", Single.class );
query.setString(0, "my id"); query.setString(0, "my id");
list = query.list(); list = query.list();
assertTrue(list.size()==1); assertTrue(list.size()==1);
session.connection().commit();
session.close();
session.getTransaction().commit();
session.close();
} }
@Test @Test
@FailureExpected( jiraKey = "unknown" ) @FailureExpected( jiraKey = "unknown" )
public void testReturnPropertyComponentRename() throws HibernateException, SQLException { public void testReturnPropertyComponentRename() throws HibernateException, SQLException {
// failure expected because this was a regression introduced previously which needs to get tracked down. // failure expected because this was a regression introduced previously which needs to get tracked down.
Session session = openSession(); Componentizable componentizable = setupComponentData();
Componentizable componentizable = setupComponentData(session);
Session session = openSession();
session.beginTransaction();
Query namedQuery = session.getNamedQuery("queryComponentWithOtherColumn"); Query namedQuery = session.getNamedQuery("queryComponentWithOtherColumn");
List list = namedQuery.list(); List list = namedQuery.list();
@ -506,11 +515,8 @@ public class SQLLoaderTest extends LegacyTestCase {
assertEquals( "flakky comp", ( (Componentizable) list.get(0) ).getComponent().getName() ); assertEquals( "flakky comp", ( (Componentizable) list.get(0) ).getComponent().getName() );
session.clear(); session.clear();
session.delete(componentizable); session.delete(componentizable);
session.flush(); session.getTransaction().commit();
session.connection().commit();
session.close(); session.close();
} }
@ -525,29 +531,28 @@ public class SQLLoaderTest extends LegacyTestCase {
} }
private void componentTest(String sql) throws SQLException { private void componentTest(String sql) throws SQLException {
Session session = openSession(); Componentizable c = setupComponentData();
Componentizable c = setupComponentData( session );
SQLQuery q = session.createSQLQuery( sql ) Session session = openSession();
.addEntity( "comp", Componentizable.class ); session.beginTransaction();
SQLQuery q = session.createSQLQuery( sql ).addEntity( "comp", Componentizable.class );
List list = q.list(); List list = q.list();
assertEquals(list.size(),1); assertEquals(list.size(),1);
Componentizable co = (Componentizable) list.get(0); Componentizable co = (Componentizable) list.get(0);
assertEquals(c.getNickName(), co.getNickName()); assertEquals(c.getNickName(), co.getNickName());
assertEquals(c.getComponent().getName(), co.getComponent().getName()); assertEquals(c.getComponent().getName(), co.getComponent().getName());
assertEquals(c.getComponent().getSubComponent().getSubName(), co.getComponent().getSubComponent().getSubName()); assertEquals(c.getComponent().getSubComponent().getSubName(), co.getComponent().getSubComponent().getSubName());
session.delete(co); session.delete( co );
session.flush(); session.getTransaction().commit();
session.connection().commit();
session.close(); session.close();
} }
private Componentizable setupComponentData(Session session) throws SQLException { private Componentizable setupComponentData() throws SQLException {
Session session = sessionFactory().openSession();
session.beginTransaction();
Componentizable c = new Componentizable(); Componentizable c = new Componentizable();
c.setNickName("Flacky"); c.setNickName("Flacky");
Component component = new Component(); Component component = new Component();
@ -559,11 +564,9 @@ public class SQLLoaderTest extends LegacyTestCase {
c.setComponent(component); c.setComponent(component);
session.save(c); session.save(c);
session.getTransaction().commit();
session.flush();
session.connection().commit();
session.clear(); session.clear();
return c; return c;
} }
@ -571,6 +574,7 @@ public class SQLLoaderTest extends LegacyTestCase {
@SkipForDialect( MySQLDialect.class ) @SkipForDialect( MySQLDialect.class )
public void testFindSimpleBySQL() throws Exception { public void testFindSimpleBySQL() throws Exception {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
Category s = new Category(); Category s = new Category();
s.setName(String.valueOf(nextLong++)); s.setName(String.valueOf(nextLong++));
session.save(s); session.save(s);
@ -583,7 +587,7 @@ public class SQLLoaderTest extends LegacyTestCase {
assertNotNull(list); assertNotNull(list);
assertTrue(list.size() > 0); assertTrue(list.size() > 0);
assertTrue(list.get(0) instanceof Category); assertTrue(list.get(0) instanceof Category);
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
// How do we handle objects with composite id's ? (such as Single) // How do we handle objects with composite id's ? (such as Single)
} }
@ -591,16 +595,19 @@ public class SQLLoaderTest extends LegacyTestCase {
@Test @Test
public void testFindBySQLSimpleByDiffSessions() throws Exception { public void testFindBySQLSimpleByDiffSessions() throws Exception {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
Category s = new Category(); Category s = new Category();
s.setName(String.valueOf(nextLong++)); s.setName(String.valueOf(nextLong++));
session.save(s); session.save(s);
session.flush(); session.getTransaction().commit();
session.connection().commit();
session.close(); session.close();
if ( getDialect() instanceof MySQLDialect ) return; if ( getDialect() instanceof MySQLDialect ) {
return;
}
session = openSession(); session = openSession();
session.beginTransaction();
Query query = session.createSQLQuery( "select s.category_key_col as {category.id}, s.name as {category.name}, s.\"assign-able-id\" as {category.assignable} from {category} s" ) Query query = session.createSQLQuery( "select s.category_key_col as {category.id}, s.name as {category.name}, s.\"assign-able-id\" as {category.assignable} from {category} s" )
.addEntity( "category", Category.class ); .addEntity( "category", Category.class );
@ -612,13 +619,14 @@ public class SQLLoaderTest extends LegacyTestCase {
// How do we handle objects that does not have id property (such as Simple ?) // How do we handle objects that does not have id property (such as Simple ?)
// How do we handle objects with composite id's ? (such as Single) // How do we handle objects with composite id's ? (such as Single)
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testFindBySQLDiscriminatedSameSession() throws Exception { public void testFindBySQLDiscriminatedSameSession() throws Exception {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from A" ).list() ) { for ( Object entity : session.createQuery( "from A" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -655,13 +663,14 @@ public class SQLLoaderTest extends LegacyTestCase {
List list2 = session.getNamedQuery("propertyResultDiscriminator").list(); List list2 = session.getNamedQuery("propertyResultDiscriminator").list();
assertEquals(2, list2.size()); assertEquals(2, list2.size());
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@Test @Test
public void testFindBySQLDiscriminatedDiffSession() throws Exception { public void testFindBySQLDiscriminatedDiffSession() throws Exception {
Session session = openSession(); Session session = openSession();
session.beginTransaction();
for ( Object entity : session.createQuery( "from A" ).list() ) { for ( Object entity : session.createQuery( "from A" ).list() ) {
session.delete( entity ); session.delete( entity );
} }
@ -670,20 +679,19 @@ public class SQLLoaderTest extends LegacyTestCase {
B savedB = new B(); B savedB = new B();
session.save(savedB); session.save(savedB);
session.flush(); session.getTransaction().commit();
int count = session.createQuery("from A").list().size(); int count = session.createQuery("from A").list().size();
session.close(); session.close();
session = openSession(); session = openSession();
session.beginTransaction();
Query query = session.createSQLQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA" ) Query query = session.createSQLQuery( "select identifier_column as {a.id}, clazz_discriminata as {a.class}, count_ as {a.count}, name as {a.name} from TA" )
.addEntity( "a", A.class ); .addEntity( "a", A.class );
List list = query.list(); List list = query.list();
assertNotNull(list); assertNotNull(list);
assertEquals(count, list.size()); assertEquals(count, list.size());
session.connection().commit(); session.getTransaction().commit();
session.close(); session.close();
} }
@ -691,18 +699,17 @@ public class SQLLoaderTest extends LegacyTestCase {
@TestForIssue( jiraKey = "HHH-21" ) @TestForIssue( jiraKey = "HHH-21" )
public void testCompositeIdId() throws HibernateException, SQLException { public void testCompositeIdId() throws HibernateException, SQLException {
Session s = openSession(); Session s = openSession();
s.beginTransaction();
CompositeIdId id = new CompositeIdId(); CompositeIdId id = new CompositeIdId();
id.setName("Max"); id.setName("Max");
id.setSystem("c64"); id.setSystem("c64");
id.setId("games"); id.setId("games");
s.save(id); s.save(id);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
// having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it. // having a composite id with one property named id works since the map used by sqlloader to map names to properties handles it.
String sql = "select system as {c.system}, id as {c.id}, name as {c.name}, foo as {c.composite.foo}, bar as {c.composite.bar} from CompositeIdId where system=? and id=?"; String sql = "select system as {c.system}, id as {c.id}, name as {c.name}, foo as {c.composite.foo}, bar as {c.composite.bar} from CompositeIdId where system=? and id=?";
SQLQuery query = s.createSQLQuery( sql ).addEntity( "c", CompositeIdId.class ); SQLQuery query = s.createSQLQuery( sql ).addEntity( "c", CompositeIdId.class );
@ -712,23 +719,19 @@ public class SQLLoaderTest extends LegacyTestCase {
CompositeIdId id2 = (CompositeIdId) query.uniqueResult(); CompositeIdId id2 = (CompositeIdId) query.uniqueResult();
check(id, id2); check(id, id2);
s.flush(); s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
s = openSession(); s = openSession();
s.beginTransaction();
CompositeIdId useForGet = new CompositeIdId(); CompositeIdId useForGet = new CompositeIdId();
useForGet.setSystem("c64"); useForGet.setSystem("c64");
useForGet.setId("games"); useForGet.setId("games");
// this doesn't work since the verification does not take column span into respect! // this doesn't work since the verification does not take column span into respect!
CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet); CompositeIdId getted = (CompositeIdId) s.get(CompositeIdId.class, useForGet);
check(id,getted); check(id,getted);
s.getTransaction().commit();
s.connection().commit();
s.close(); s.close();
} }
private void check(CompositeIdId id, CompositeIdId id2) { private void check(CompositeIdId id, CompositeIdId id2) {

View File

@ -492,35 +492,5 @@ public class CMTTest extends BaseCoreFunctionalTestCase {
TestingJtaBootstrap.INSTANCE.getTransactionManager().commit(); TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
} }
@Test
public void testAggressiveReleaseWithConnectionRetreival() throws Exception {
TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
Session s = openSession();
Map item1 = new HashMap();
item1.put( "name", "Item - 1" );
item1.put( "description", "The first item" );
s.save( "Item", item1 );
Map item2 = new HashMap();
item2.put( "name", "Item - 2" );
item2.put( "description", "The second item" );
s.save( "Item", item2 );
TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
try {
TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
s = sessionFactory().getCurrentSession();
s.createQuery( "from Item" ).scroll().next();
s.connection();
TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
}
finally {
TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
s = openSession();
s.createQuery( "delete from Item" ).executeUpdate();
TestingJtaBootstrap.INSTANCE.getTransactionManager().commit();
}
}
} }

View File

@ -34,6 +34,7 @@ import org.jboss.logging.Logger;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.Interceptor; import org.hibernate.Interceptor;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.annotations.common.util.ReflectHelper; import org.hibernate.annotations.common.util.ReflectHelper;
import org.hibernate.cfg.Environment; import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionFactoryImplementor;
@ -100,10 +101,11 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl {
@Override @Override
protected Session getRawSession() { protected Session getRawSession() {
if ( session == null ) { if ( session == null ) {
Interceptor interceptor = null; SessionBuilder sessionBuilder = getEntityManagerFactory().getSessionFactory().withOptions();
if (sessionInterceptorClass != null) { if (sessionInterceptorClass != null) {
try { try {
interceptor = (Interceptor) sessionInterceptorClass.newInstance(); Interceptor interceptor = (Interceptor) sessionInterceptorClass.newInstance();
sessionBuilder.interceptor( interceptor );
} }
catch (InstantiationException e) { catch (InstantiationException e) {
throw new PersistenceException("Unable to instanciate session interceptor: " + sessionInterceptorClass, e); throw new PersistenceException("Unable to instanciate session interceptor: " + sessionInterceptorClass, e);
@ -115,9 +117,8 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl {
throw new PersistenceException("Session interceptor does not implement Interceptor: " + sessionInterceptorClass, e); throw new PersistenceException("Session interceptor does not implement Interceptor: " + sessionInterceptorClass, e);
} }
} }
final boolean autoJoinTransactions = ( getTransactionType() != PersistenceUnitTransactionType.JTA ); sessionBuilder.autoJoinTransactions( getTransactionType() != PersistenceUnitTransactionType.JTA );
final SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) getEntityManagerFactory().getSessionFactory() ); session = sessionBuilder.openSession();
session = sfi.openSession( interceptor, autoJoinTransactions );
if ( persistenceContextType == PersistenceContextType.TRANSACTION ) { if ( persistenceContextType == PersistenceContextType.TRANSACTION ) {
( (SessionImplementor) session ).setAutoClear( true ); ( (SessionImplementor) session ).setAutoClear( true );
} }

View File

@ -45,6 +45,7 @@ import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor; import org.hibernate.engine.SessionImplementor;
import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.AbstractReturningWork;
import org.hibernate.jdbc.Work; import org.hibernate.jdbc.Work;
import org.hibernate.mapping.Collection; import org.hibernate.mapping.Collection;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
@ -100,7 +101,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
} }
protected Session openSession(Interceptor interceptor) throws HibernateException { protected Session openSession(Interceptor interceptor) throws HibernateException {
session = sessionFactory().openSession(interceptor); session = sessionFactory().withOptions().interceptor( interceptor ).openSession();
return session; return session;
} }
@ -108,6 +109,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
// before/after test class ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // before/after test class ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@BeforeClassOnce @BeforeClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
private void buildSessionFactory() { private void buildSessionFactory() {
configuration = buildConfiguration(); configuration = buildConfiguration();
serviceRegistry = buildServiceRegistry( configuration ); serviceRegistry = buildServiceRegistry( configuration );
@ -266,6 +268,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
} }
@AfterClassOnce @AfterClassOnce
@SuppressWarnings( {"UnusedDeclaration"})
private void releaseSessionFactory() { private void releaseSessionFactory() {
if ( sessionFactory == null ) { if ( sessionFactory == null ) {
return; return;
@ -277,6 +280,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
@OnFailure @OnFailure
@OnExpectedFailure @OnExpectedFailure
@SuppressWarnings( {"UnusedDeclaration"})
public void onFailure() { public void onFailure() {
if ( rebuildSessionFactoryOnError() ) { if ( rebuildSessionFactoryOnError() ) {
rebuildSessionFactory(); rebuildSessionFactory();
@ -350,7 +354,7 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
Map<String,Integer> items = new HashMap<String,Integer>(); Map<String,Integer> items = new HashMap<String,Integer>();
if ( !list.isEmpty() ) { if ( !list.isEmpty() ) {
for ( Object element : list ) { for ( Object element : list ) {
Integer l = (Integer) items.get( tmpSession.getEntityName( element ) ); Integer l = items.get( tmpSession.getEntityName( element ) );
if ( l == null ) { if ( l == null ) {
l = Integer.valueOf( 0 ); l = Integer.valueOf( 0 );
} }
@ -376,7 +380,14 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
Session testSession = null; Session testSession = null;
try { try {
testSession = openSession(); testSession = openSession();
isolation = testSession.connection().getTransactionIsolation(); isolation = testSession.doReturningWork(
new AbstractReturningWork<Integer>() {
@Override
public Integer execute(Connection connection) throws SQLException {
return connection.getTransactionIsolation();
}
}
);
} }
catch( Throwable ignore ) { catch( Throwable ignore ) {
} }