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
*/
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.
*
@ -105,7 +112,9 @@ public interface Session extends SharedSessionContract {
*
* @param entityMode The entity mode to use for the new session.
* @return The new session
* @deprecated
*/
@Deprecated
public Session getSession(EntityMode entityMode);
/**
@ -170,21 +179,6 @@ public interface Session extends SharedSessionContract {
*/
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
* 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}
*
* @see SessionFactory#openSession(java.sql.Connection)
* @see SessionFactory#openSession(java.sql.Connection, Interceptor)
* @see #reconnect(Connection)
*/
Connection disconnect() throws HibernateException;
@ -866,6 +858,7 @@ public interface Session extends SharedSessionContract {
* Reconnect to the given JDBC connection.
*
* @param connection a JDBC connection
*
* @see #disconnect()
*/
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.
* 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);

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
*/
public interface SessionFactory extends Referenceable, Serializable {
/**
* Obtain a {@link Session} builder.
*
* @return The session builder
*/
public SessionBuilder withOptions();
/**
* Open a {@link Session}.
* <p/>
@ -60,57 +67,10 @@ public interface SessionFactory extends Referenceable, Serializable {
*
* @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;
/**
* 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"
* 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.
*/
protected Session buildOrObtainSession() {
return factory.openSession(
null,
isAutoFlushEnabled(),
isAutoCloseEnabled(),
getConnectionReleaseMode()
);
return factory.withOptions()
.autoClose( isAutoCloseEnabled() )
.connectionReleaseMode( getConnectionReleaseMode() )
.flushBeforeCompletion( isAutoFlushEnabled() )
.openSession();
}
/**

View File

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

View File

@ -217,29 +217,6 @@ public interface SessionFactoryImplementor extends Mapping, SessionFactory {
*/
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
* 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.QueryException;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.StatelessSession;
@ -101,6 +102,7 @@ import org.hibernate.engine.profile.Fetch;
import org.hibernate.engine.profile.FetchProfile;
import org.hibernate.engine.query.QueryPlanCache;
import org.hibernate.engine.query.sql.NativeSQLQuerySpecification;
import org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl;
import org.hibernate.engine.transaction.spi.TransactionEnvironment;
import org.hibernate.exception.SQLExceptionConverter;
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.SessionFactoryServiceRegistryFactory;
import org.hibernate.stat.Statistics;
import org.hibernate.stat.internal.ConcurrentStatisticsImpl;
import org.hibernate.stat.spi.StatisticsImplementor;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
@ -528,6 +529,38 @@ public final class SessionFactoryImpl
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
public void addObserver(SessionFactoryObserver observer) {
this.observer.addObserver( observer );
@ -658,118 +691,6 @@ public final class SessionFactoryImpl
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 {
EntityPersister result = (EntityPersister) entityPersisters.get(entityName);
if (result==null) {
@ -1391,4 +1312,89 @@ public final class SessionFactoryImpl
}
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.Session;
import org.hibernate.SessionException;
import org.hibernate.SharedSessionBuilder;
import org.hibernate.Transaction;
import org.hibernate.TransientObjectException;
import org.hibernate.TypeHelper;
@ -179,13 +180,14 @@ public final class SessionImpl
private transient FlushMode flushMode = FlushMode.AUTO;
private transient CacheMode cacheMode = CacheMode.NORMAL;
private transient EntityMode entityMode = EntityMode.POJO;
private transient boolean autoClear; //for EJB3
private transient boolean autoJoinTransactions = true;
private transient int dontFlushFromFind = 0;
private transient boolean flushBeforeCompletionEnabled;
private transient boolean autoCloseSessionEnabled;
private transient int dontFlushFromFind = 0;
private transient LoadQueryInfluencers loadQueryInfluencers;
private transient Session rootSession;
@ -223,7 +225,9 @@ public final class SessionImpl
*
* @param connection The user-supplied connection to use for this session.
* @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 interceptor The interceptor to be applied to this session
* @param entityMode The entity-mode for this session
@ -234,7 +238,7 @@ public final class SessionImpl
SessionImpl(
final Connection connection,
final SessionFactoryImpl factory,
final boolean autoClose,
final TransactionCoordinatorImpl transactionCoordinator,
final boolean autoJoinTransactions,
final long timestamp,
final Interceptor interceptor,
@ -254,10 +258,18 @@ public final class SessionImpl
this.connectionReleaseMode = connectionReleaseMode;
this.autoJoinTransactions = autoJoinTransactions;
if ( transactionCoordinator == null ) {
this.transactionCoordinator = new TransactionCoordinatorImpl( connection, this );
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 );
@ -266,6 +278,11 @@ public final class SessionImpl
LOG.debugf("Opened session at timestamp: %s", timestamp);
}
@Override
public SharedSessionBuilder sessionWithOptions() {
return new SharedSessionBuilderImpl( this );
}
public Session getSession(EntityMode entityMode) {
if ( this.entityMode == entityMode ) {
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 {
public String resolveEntityName(Object entity) {
String entityName = interceptor.getEntityName( entity );

View File

@ -22,21 +22,25 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.jmx;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
import java.sql.Connection;
import java.util.Map;
import java.util.Set;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.jboss.logging.Logger;
import org.hibernate.AssertionFailure;
import org.hibernate.Cache;
import org.hibernate.HibernateException;
import org.hibernate.HibernateLogger;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.TypeHelper;
@ -47,7 +51,6 @@ import org.hibernate.impl.SessionFactoryObjectFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.metadata.CollectionMetadata;
import org.hibernate.stat.Statistics;
import org.jboss.logging.Logger;
/**
* 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() );
}
public Session openSession(Connection connection, Interceptor interceptor) {
return getImpl().openSession(connection, interceptor);
}
public Session openSession(Interceptor interceptor) throws HibernateException {
return getImpl().openSession(interceptor);
@Override
public SessionBuilder withOptions() {
return getImpl().withOptions();
}
public Session openSession() throws HibernateException {
return getImpl().openSession();
}
public Session openSession(Connection conn) {
return getImpl().openSession(conn);
}
public Session getCurrentSession() {
return getImpl().getCurrentSession();
}

View File

@ -196,7 +196,7 @@ public class AggressiveReleaseTest extends ConnectionManagementTestCase {
prepare();
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" );
session.save( silly );
@ -215,36 +215,6 @@ public class AggressiveReleaseTest extends ConnectionManagementTestCase {
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
public void testConnectionMaintanenceDuringFlush() throws Throwable {
prepare();

View File

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

View File

@ -23,6 +23,7 @@
*/
package org.hibernate.test.connections;
import java.sql.Connection;
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.tool.hbm2ddl.SchemaExport;
import org.junit.Before;
import org.hibernate.testing.AfterClassOnce;
import org.hibernate.testing.BeforeClassOnce;
import org.hibernate.testing.env.ConnectionProviderBuilder;
@ -70,7 +69,7 @@ public class SuppliedConnectionTest extends ConnectionManagementTestCase {
@Override
protected Session getSessionUnderTest() throws Throwable {
connectionUnderTest = cp.getConnection();
return sessionFactory().openSession( connectionUnderTest );
return sessionFactory().withOptions().connection( connectionUnderTest ).openSession();
}
@Override

View File

@ -22,6 +22,8 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.join;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
@ -29,6 +31,7 @@ import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.jdbc.AbstractWork;
import org.junit.Test;
@ -137,7 +140,14 @@ public class JoinTest extends BaseCoreFunctionalTestCase {
s.clear();
// 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();
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 {
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();
assertFalse( session.getTransactionCoordinator().isSynchronizationRegistered() );
@ -100,7 +100,7 @@ public class TransactionJoiningTest extends AbstractJPATest {
TestingJtaBootstrap.INSTANCE.getTransactionManager().begin();
assertTrue( JtaStatusHelper.isActive( TestingJtaBootstrap.INSTANCE.getTransactionManager() ) );
SessionImplementor session = (SessionImplementor) sessionFactory().openSession( false );
SessionImplementor session = (SessionImplementor) sessionFactory().withOptions().autoJoinTransactions( false ).openSession();
session.getFlushMode();
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,6 +2,8 @@
package org.hibernate.test.legacy;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
@ -16,6 +18,7 @@ import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.jdbc.Work;
import org.junit.Test;
@ -122,9 +125,16 @@ public class MultiTableTest extends LegacyTestCase {
s = openSession();
s.beginTransaction();
s.connection().createStatement().executeQuery(
"select * from leafsubsubclass sm, nonleafsubclass m, rootclass s where sm.sid=m.sid and sm.sid=s.id1_ and sm.sid=1"
).next();
s.doWork(
new Work() {
@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(
s.createQuery(
"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.engine.EntityEntry;
import org.hibernate.impl.SessionImpl;
import org.hibernate.jdbc.AbstractWork;
import org.hibernate.proxy.HibernateProxy;
import org.junit.Test;
@ -1194,7 +1195,14 @@ public class ParentChildTest extends LegacyTestCase {
public void testLoadAfterNonExists() throws HibernateException, SQLException {
Session session = openSession();
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();

View File

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

View File

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

View File

@ -492,35 +492,5 @@ public class CMTTest extends BaseCoreFunctionalTestCase {
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.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionBuilder;
import org.hibernate.annotations.common.util.ReflectHelper;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.SessionFactoryImplementor;
@ -100,10 +101,11 @@ public class EntityManagerImpl extends AbstractEntityManagerImpl {
@Override
protected Session getRawSession() {
if ( session == null ) {
Interceptor interceptor = null;
SessionBuilder sessionBuilder = getEntityManagerFactory().getSessionFactory().withOptions();
if (sessionInterceptorClass != null) {
try {
interceptor = (Interceptor) sessionInterceptorClass.newInstance();
Interceptor interceptor = (Interceptor) sessionInterceptorClass.newInstance();
sessionBuilder.interceptor( interceptor );
}
catch (InstantiationException 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);
}
}
final boolean autoJoinTransactions = ( getTransactionType() != PersistenceUnitTransactionType.JTA );
final SessionFactoryImplementor sfi = ( (SessionFactoryImplementor) getEntityManagerFactory().getSessionFactory() );
session = sfi.openSession( interceptor, autoJoinTransactions );
sessionBuilder.autoJoinTransactions( getTransactionType() != PersistenceUnitTransactionType.JTA );
session = sessionBuilder.openSession();
if ( persistenceContextType == PersistenceContextType.TRANSACTION ) {
( (SessionImplementor) session ).setAutoClear( true );
}

View File

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