/** * Create a close-suppressing proxy for the given Hibernate Session. * The proxy also prepares returned Query and Criteria objects. * @param session the Hibernate Session to create a proxy for * @return the Session proxy * @see org.hibernate.Session#close() * @see #prepareQuery * @see #prepareCriteria */ protected Session createSessionProxy(Session session) { Class<?>[] sessionIfcs; Class<?> mainIfc = (session instanceof org.hibernate.classic.Session ? org.hibernate.classic.Session.class : Session.class); if (session instanceof EventSource) { sessionIfcs = new Class<?>[] {mainIfc, EventSource.class}; } else if (session instanceof SessionImplementor) { sessionIfcs = new Class<?>[] {mainIfc, SessionImplementor.class}; } else { sessionIfcs = new Class<?>[] {mainIfc}; } return (Session) Proxy.newProxyInstance( session.getClass().getClassLoader(), sessionIfcs, new CloseSuppressingInvocationHandler(session)); }
public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { Object permission = null; String className = resultSet.getString(names[0]); String name = resultSet.getString(names[1]); String actions = resultSet.getString(names[2]); try { // TODO optimize performance by caching the constructors Class permissionClass = PermissionUserType.class.getClassLoader().loadClass(className); @SuppressWarnings("unchecked") Constructor constructor = permissionClass.getDeclaredConstructor(NAME_ACTIOS_CONSTRUCTOR_PARAMETER_TYPES); permission = constructor.newInstance(new Object[]{name, actions}); } catch (Exception e) { throw new HibernateException("couldn't create permission from database record ["+className+"|"+name+"|"+actions+"]. Does the permission class have a (String name,String actions) constructor ?", e); } return permission; }
/** * Returns the connection used by the hibernate session. * * @param doFlush * if true then the current actions are first flushed. * * @return the current database connection * @see #flush() */ public Connection getConnection(boolean doFlush) { if (doFlush) { // before returning a connection flush all other hibernate actions // to the database. flush(); } // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); final Connection connection = ((SessionImplementor) SessionHandler.getInstance().getSession()) .connection(); return connection; } finally { Thread.currentThread().setContextClassLoader(currentLoader); } }
/** * Note method sets user session information in the database and opens a connection for this. */ public Session openSession(Connection connection, Interceptor interceptor) { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final Session session = delegateSessionFactory.openSession(connection, interceptor); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
/** * Note method sets user session information in the database and opens a connection for this. */ public Session openSession(Connection connection) { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final Session session = delegateSessionFactory.openSession(connection); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
/** * Note method sets user session information in the database and opens a connection for this. */ public Session openSession(Interceptor interceptor) throws HibernateException { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final Session session = delegateSessionFactory.openSession(interceptor); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
/** * Note method sets user session information in the database and opens a connection for this. */ public StatelessSession openStatelessSession(Connection connection) { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final StatelessSession session = delegateSessionFactory.openStatelessSession(connection); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
static void identityRemove( Collection list, Object object, String entityName, SessionImplementor session) throws HibernateException { if ( object!=null && ForeignKeys.isNotTransient(entityName, object, null, session) ) { Type idType = session.getFactory().getEntityPersister(entityName).getIdentifierType(); Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, object, session); Iterator iter = list.iterator(); while ( iter.hasNext() ) { Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved(entityName, iter.next(), session); if ( idType.isEqual( idOfCurrent, idOfOld, session.getEntityMode(), session.getFactory() ) ) { iter.remove(); break; } } } }
public ScrollableResults performScroll( QueryParameters queryParameters, SessionImplementor session) throws HibernateException { if ( log.isTraceEnabled() ) { log.trace( "iterate: " + getSourceQuery() ); queryParameters.traceParameters( session.getFactory() ); } if ( translators.length != 1 ) { throw new QueryException( "implicit polymorphism not supported for scroll() queries" ); } if ( queryParameters.getRowSelection().definesLimits() && translators[0].containsCollectionFetches() ) { throw new QueryException( "firstResult/maxResults not supported in conjunction with scroll() of a query containing collection fetches" ); } return translators[0].scroll( queryParameters, session ); }
public Object replace( Object original, Object target, SessionImplementor session, Object owner, Map copyCache, ForeignKeyDirection foreignKeyDirection) throws HibernateException { boolean include; if ( isAssociationType() ) { AssociationType atype = (AssociationType) this; include = atype.getForeignKeyDirection()==foreignKeyDirection; } else { include = ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT==foreignKeyDirection; } return include ? replace(original, target, session, owner, copyCache) : target; }
public static FieldInterceptor injectFieldInterceptor( Object entity, String entityName, Set uninitializedFieldNames, SessionImplementor session) { if ( entity != null ) { Class[] definedInterfaces = entity.getClass().getInterfaces(); for ( int i = 0; i < definedInterfaces.length; i++ ) { if ( "net.sf.cglib.transform.impl.InterceptFieldEnabled".equals( definedInterfaces[i].getName() ) ) { // we have a CGLIB enhanced entity return CGLIBHelper.injectFieldInterceptor( entity, entityName, uninitializedFieldNames, session ); } else if ( "org.hibernate.bytecode.javassist.FieldHandled".equals( definedInterfaces[i].getName() ) ) { // we have a Javassist enhanced entity return JavassistHelper.injectFieldInterceptor( entity, entityName, uninitializedFieldNames, session ); } } } return null; }
public boolean isModified(Object old, Object current, boolean[] checkable, SessionImplementor session) throws HibernateException { if ( current == null ) { return old != null; } if ( old == null ) { return current != null; } Object[] currentValues = getPropertyValues( current, session ); Object[] oldValues = ( Object[] ) old; int loc = 0; for ( int i = 0; i < currentValues.length; i++ ) { int len = propertyTypes[i].getColumnSpan( session.getFactory() ); boolean[] subcheckable = new boolean[len]; System.arraycopy( checkable, loc, subcheckable, 0, len ); if ( propertyTypes[i].isModified( oldValues[i], currentValues[i], subcheckable, session ) ) { return true; } loc += len; } return false; }
/** * Execute an SQL query and attempt to instantiate instances of the class mapped by the given * persister from each row of the <tt>ResultSet</tt>. If an object is supplied, will attempt to * initialize that object. If a collection is supplied, attempt to initialize that collection. */ private List doQueryAndInitializeNonLazyCollections(final SessionImplementor session, final QueryParameters queryParameters, final boolean returnProxies) throws HibernateException, SQLException { final PersistenceContext persistenceContext = session.getPersistenceContext(); persistenceContext.beforeLoad(); List result; try { result = doQuery( session, queryParameters, returnProxies ); } finally { persistenceContext.afterLoad(); } persistenceContext.initializeNonLazyCollections(); return result; }
private static EntityKey getOptionalObjectKey(QueryParameters queryParameters, SessionImplementor session) { final Object optionalObject = queryParameters.getOptionalObject(); final Serializable optionalId = queryParameters.getOptionalId(); final String optionalEntityName = queryParameters.getOptionalEntityName(); if ( optionalObject != null && optionalEntityName != null ) { return new EntityKey( optionalId, session.getEntityPersister( optionalEntityName, optionalObject ), session.getEntityMode() ); } else { return null; } }
/** * Bind positional parameter values to the <tt>PreparedStatement</tt> * (these are parameters specified by a JDBC-style ?). */ private int bindPositionalParameters(final PreparedStatement st, final QueryParameters queryParameters, final int start, final SessionImplementor session) throws SQLException, HibernateException { final Object[] values = queryParameters .getFilteredPositionalParameterValues(); final Type[] types = queryParameters .getFilteredPositionalParameterTypes(); int span = 0; for (int i = 0; i < values.length; i++) { types[i].nullSafeSet( st, values[i], start + span, session ); span += types[i].getColumnSpan( session.getFactory() ); } return span; }
public EntityUpdateAction( final Serializable id, final Object[] state, final int[] dirtyProperties, final boolean hasDirtyCollection, final Object[] previousState, final Object previousVersion, final Object nextVersion, final Object instance, final Object rowId, final EntityPersister persister, final SessionImplementor session) throws HibernateException { super( session, id, instance, persister ); this.state = state; this.previousState = previousState; this.previousVersion = previousVersion; this.nextVersion = nextVersion; this.dirtyFields = dirtyProperties; this.hasDirtyCollection = hasDirtyCollection; this.rowId = rowId; }
public Object assemble( Serializable oid, SessionImplementor session, Object owner) throws HibernateException { //TODO: currently broken for unique-key references (does not detect // change to unique key property of the associated object) Serializable id = assembleId( oid, session ); if ( isNotEmbedded( session ) ) { return id; } if ( id == null ) { return null; } else { return resolveIdentifier( id, session ); } }
protected CollectionInitializer getAppropriateInitializer(Serializable key, SessionImplementor session) { if ( queryLoaderName != null ) { //if there is a user-specified loader, return that //TODO: filters!? return initializer; } CollectionInitializer subselectInitializer = getSubselectInitializer( key, session ); if ( subselectInitializer != null ) { return subselectInitializer; } else if ( session.getEnabledFilters().isEmpty() ) { return initializer; } else { return createCollectionInitializer( session.getEnabledFilters() ); } }
/** * Return the query results, using the query cache, called * by subclasses that implement cacheable queries */ protected List list( final SessionImplementor session, final QueryParameters queryParameters, final Set querySpaces, final Type[] resultTypes) throws HibernateException { final boolean cacheable = factory.getSettings().isQueryCacheEnabled() && queryParameters.isCacheable(); if ( cacheable ) { return listUsingQueryCache( session, queryParameters, querySpaces, resultTypes ); } else { return listIgnoreQueryCache( session, queryParameters ); } }
public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) throws StaleObjectStateException, JDBCException { if ( getLockMode().greaterThan( LockMode.READ ) ) { log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" ); } super.lock( id, version, object, timeout, session ); }
public void lock(Serializable id, Object version, Object object, SessionImplementor session) throws StaleObjectStateException, JDBCException { if ( getLockMode().greaterThan( LockMode.READ ) ) { log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" ); } super.lock( id, version, object, session ); }
/** * Hibernate 3.1 implementation of ID transferral. */ @Override protected void entityIsTransient(MergeEvent event, Map copyCache) { super.entityIsTransient(event, copyCache); SessionImplementor session = event.getSession(); EntityPersister persister = session.getEntityPersister(event.getEntityName(), event.getEntity()); // Extract id from merged copy (which is currently registered with Session). Serializable id = persister.getIdentifier(event.getResult(), session.getEntityMode()); // Set id on original object (which remains detached). persister.setIdentifier(event.getOriginal(), id, session.getEntityMode()); }
@Override public void afterCompletion(int status) { try { if (!this.hibernateTransactionCompletion || !this.newSession) { // No Hibernate TransactionManagerLookup: apply afterTransactionCompletion callback. // Always perform explicit afterTransactionCompletion callback for pre-bound Session, // even with Hibernate TransactionManagerLookup (which only applies to new Sessions). Session session = this.sessionHolder.getSession(); // Provide correct transaction status for releasing the Session's cache locks, // if possible. Else, closing will release all cache locks assuming a rollback. try { if (session instanceof SessionImplementor) { ((SessionImplementor) session).afterTransactionCompletion(status == STATUS_COMMITTED, null); } } finally { // Close the Hibernate Session here if necessary // (closed in beforeCompletion in case of TransactionManagerLookup). if (this.newSession) { SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, this.sessionFactory); } else if (!this.hibernateTransactionCompletion) { session.disconnect(); } } } if (!this.newSession && status != STATUS_COMMITTED) { // Clear all pending inserts/updates/deletes in the Session. // Necessary for pre-bound Sessions, to avoid inconsistent state. this.sessionHolder.getSession().clear(); } } finally { if (this.sessionHolder.doesNotHoldNonDefaultSession()) { this.sessionHolder.setSynchronizedWithTransaction(false); } } }
/** * Hibernate makes {@link Class#getClass()} diffficult ... * @param example The class that we want to call {@link Class#getClass()} on * @return The type of the given object */ public Class getClass(Object example) { if (example instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) example; LazyInitializer initializer = proxy.getHibernateLazyInitializer(); SessionImplementor implementor = initializer.getSession(); if (initializer.isUninitialized()) { try { // getImplementation is going to want to talk to a session if (implementor.isClosed()) { // Give up and return example.getClass(); return example.getClass(); } } catch (NoSuchMethodError ex) { // We must be using Hibernate 3.0/3.1 which doesn't have // this method } } return initializer.getImplementation().getClass(); } else { return example.getClass(); } }
/** * Hibernate makes {@link Class#getClass()} difficult ... * @param example The class that we want to call {@link Class#getClass()} on * @return The type of the given object */ public Class<?> getClass(Object example) { if (example instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) example; LazyInitializer initializer = proxy.getHibernateLazyInitializer(); SessionImplementor implementor = initializer.getSession(); if (initializer.isUninitialized()) { try { // getImplementation is going to want to talk to a session if (implementor.isClosed()) { // Give up and return example.getClass(); return example.getClass(); } } catch (NoSuchMethodError ex) { // We must be using Hibernate 3.0/3.1 which doesn't have // this method } } return initializer.getImplementation().getClass(); } else { return example.getClass(); } }
@Override public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { final BaseOBObjectDef bob = (BaseOBObjectDef) obj; if (bob.getId() != null) { return ((String) bob.getId()).toUpperCase(); } String result = ((String) super.generate(session, obj)).toUpperCase(); result = result.replace("-", ""); if (result.length() != 32) { throw new OBException("Generating UUID of wrong length: " + result); } return result; }
/** * Note method sets user session information in the database and opens a connection for this. */ public StatelessSession openStatelessSession() { // NOTE: workaround for this issue: // http://opensource.atlassian.com/projects/hibernate/browse/HHH-3529 final StatelessSession session = delegateSessionFactory.openStatelessSession(); final ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(BorrowedConnectionProxy.class.getClassLoader()); Connection conn = ((SessionImplementor) session).connection(); SessionInfo.initDB(conn, OBPropertiesProvider.getInstance().getOpenbravoProperties() .getProperty("bbdd.rdbms")); SessionInfo.setDBSessionInfo(conn); } finally { Thread.currentThread().setContextClassLoader(currentLoader); } return session; }
@Override public Serializable generate(SessionImplementor session, Object obj) throws HibernateException { final BaseOBObjectDef bob = (BaseOBObjectDef) obj; if (bob.getId() != null) { return ((String) bob.getId()).toUpperCase(); } return ((String) super.generate(session, obj)).toUpperCase(); }
public void nullSafeSet( PreparedStatement st, Object value, int index, boolean[] settable, SessionImplementor session) throws HibernateException, SQLException { if ( settable[0] ) nullSafeSet(st, value, index, session); }
public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister, Serializable key) { if ( session.getEntityMode()==EntityMode.DOM4J ) { return new PersistentMapElementHolder(session, persister, key); } else { return new PersistentMap(session); } }
/** * Determine if any of the given field values are dirty, returning an array containing * indices of the dirty fields. * <p/> * If it is determined that no fields are dirty, null is returned. * * @param properties The property definitions * @param currentState The current state of the entity * @param previousState The baseline state of the entity * @param includeColumns Columns to be included in the dirty checking, per property * @param anyUninitializedProperties Does the entity currently hold any uninitialized property values? * @param session The session from which the dirty check request originated. * @return Array containing indices of the dirty properties, or null if no properties considered dirty. */ public static int[] findDirty( final StandardProperty[] properties, final Object[] currentState, final Object[] previousState, final boolean[][] includeColumns, final boolean anyUninitializedProperties, final SessionImplementor session) { int[] results = null; int count = 0; int span = properties.length; for ( int i = 0; i < span; i++ ) { final boolean dirty = currentState[i] != LazyPropertyInitializer.UNFETCHED_PROPERTY && properties[i].isDirtyCheckable( anyUninitializedProperties ) && properties[i].getType().isDirty( previousState[i], currentState[i], includeColumns[i], session ); if ( dirty ) { if ( results == null ) { results = new int[span]; } results[count++] = i; } } if ( count == 0 ) { return null; } else { int[] trimmed = new int[count]; System.arraycopy( results, 0, trimmed, 0, count ); return trimmed; } }
/** * @see EntityPersister#lock(Serializable, Object, Object, LockMode, SessionImplementor) */ public void lock( Serializable id, Object version, Object object, LockMode lockMode, SessionImplementor session ) throws HibernateException { throw new UnsupportedOperationException(); }
public void initialize(Serializable key, SessionImplementor session) throws HibernateException { if ( log.isDebugEnabled() ) { log.debug( "initializing collection: " + persister.getRole() + " using named query: " + queryName ); } //TODO: is there a more elegant way than downcasting? AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedSQLQuery(queryName); if ( query.getNamedParameters().length>0 ) { query.setParameter( query.getNamedParameters()[0], key, persister.getKeyType() ); } else { query.setParameter( 0, key, persister.getKeyType() ); } query.setCollectionKey( key ) .setFlushMode( FlushMode.MANUAL ) .list(); }
SQLQueryImpl( final String sql, final String returnAliases[], final Class returnClasses[], final SessionImplementor session, ParameterMetadata parameterMetadata) { this( sql, returnAliases, returnClasses, null, session, null, null, parameterMetadata ); }
public AccessCallback buildCallback(final SessionImplementor session) { return new AccessCallback() { public long getNextValue() { return ( ( Number ) doWorkInNewTransaction( session ) ).longValue(); } }; }