Package org.hibernate.engine.spi

Examples of org.hibernate.engine.spi.SessionImplementor


    return intercepted;
  }

  protected boolean handleInterception(FlushEntityEvent event) {
    SessionImplementor session = event.getSession();
    EntityEntry entry = event.getEntityEntry();
    EntityPersister persister = entry.getPersister();
    Object entity = event.getEntity();

    //give the Interceptor a chance to modify property values
View Full Code Here


   */
  protected void dirtyCheck(final FlushEntityEvent event) throws HibernateException {

    final Object entity = event.getEntity();
    final Object[] values = event.getPropertyValues();
    final SessionImplementor session = event.getSession();
    final EntityEntry entry = event.getEntityEntry();
    final EntityPersister persister = entry.getPersister();
    final Serializable id = entry.getId();
    final Object[] loadedState = entry.getLoadedState();

    int[] dirtyProperties = session.getInterceptor().findDirty(
        entity,
        id,
        values,
        loadedState,
        persister.getPropertyNames(),
        persister.getPropertyTypes()
    );

    if ( dirtyProperties == null ) {
      if ( entity instanceof SelfDirtinessTracker ) {
        if ( ( (SelfDirtinessTracker) entity ).$$_hibernate_hasDirtyAttributes() ) {
          dirtyProperties = persister.resolveAttributeIndexes( ( (SelfDirtinessTracker) entity ).$$_hibernate_getDirtyAttributes() );
        }
      }
      else {
        // see if the custom dirtiness strategy can tell us...
        class DirtyCheckContextImpl implements CustomEntityDirtinessStrategy.DirtyCheckContext {
          int[] found;

          @Override
          public void doDirtyChecking(CustomEntityDirtinessStrategy.AttributeChecker attributeChecker) {
            found = new DirtyCheckAttributeInfoImpl( event ).visitAttributes( attributeChecker );
            if ( found != null && found.length == 0 ) {
              found = null;
            }
          }
        }
        DirtyCheckContextImpl context = new DirtyCheckContextImpl();
        session.getFactory().getCustomEntityDirtinessStrategy().findDirty(
            entity,
            persister,
            (Session) session,
            context
        );
        dirtyProperties = context.found;
      }
    }

    event.setDatabaseSnapshot( null );

    final boolean interceptorHandledDirtyCheck;
    boolean cannotDirtyCheck;

    if ( dirtyProperties == null ) {
      // Interceptor returned null, so do the dirtycheck ourself, if possible
      try {
        session.getEventListenerManager().dirtyCalculationStart();

        interceptorHandledDirtyCheck = false;
        // object loaded by update()
        cannotDirtyCheck = loadedState == null;
        if ( !cannotDirtyCheck ) {
          // dirty check against the usual snapshot of the entity
          dirtyProperties = persister.findDirty( values, loadedState, entity, session );
        }
        else if ( entry.getStatus() == Status.DELETED && !event.getEntityEntry().isModifiableEntity() ) {
          // A non-modifiable (e.g., read-only or immutable) entity needs to be have
          // references to transient entities set to null before being deleted. No other
          // fields should be updated.
          if ( values != entry.getDeletedState() ) {
            throw new IllegalStateException(
                "Entity has status Status.DELETED but values != entry.getDeletedState"
            );
          }
          // Even if loadedState == null, we can dirty-check by comparing currentState and
          // entry.getDeletedState() because the only fields to be updated are those that
          // refer to transient entities that are being set to null.
          // - currentState contains the entity's current property values.
          // - entry.getDeletedState() contains the entity's current property values with
          //   references to transient entities set to null.
          // - dirtyProperties will only contain properties that refer to transient entities
          final Object[] currentState = persister.getPropertyValues( event.getEntity() );
          dirtyProperties = persister.findDirty( entry.getDeletedState(), currentState, entity, session );
          cannotDirtyCheck = false;
        }
        else {
          // dirty check against the database snapshot, if possible/necessary
          final Object[] databaseSnapshot = getDatabaseSnapshot( session, persister, id );
          if ( databaseSnapshot != null ) {
            dirtyProperties = persister.findModified( databaseSnapshot, values, entity, session );
            cannotDirtyCheck = false;
            event.setDatabaseSnapshot( databaseSnapshot );
          }
        }
      }
      finally {
        session.getEventListenerManager().dirtyCalculationEnd( dirtyProperties != null );
      }
    }
    else {
      // the Interceptor handled the dirty checking
      cannotDirtyCheck = false;
View Full Code Here

    try {
      // do the translation
      org.hibernate.Query hqlQuery = getSession().createQuery( jpaqlString );

      // make sure the query is a select -> HHH-7192
      final SessionImplementor session = unwrap( SessionImplementor.class );
      final HQLQueryPlan queryPlan = session.getFactory().getQueryPlanCache().getHQLQueryPlan(
          jpaqlString,
          false,
          session.getLoadQueryInfluencers().getEnabledFilters()
      );
      if ( queryPlan.getTranslators()[0].isManipulationStatement() ) {
        throw new IllegalArgumentException( "Update/delete queries cannot be typed" );
      }
View Full Code Here

          LOG.callingJoinTransactionOnNonJtaEntityManager();
      }
      return;
    }

    final SessionImplementor session = (SessionImplementor) getSession();
    final TransactionCoordinator transactionCoordinator = session.getTransactionCoordinator();
    final TransactionImplementor transaction = transactionCoordinator.getTransaction();

    transaction.markForJoin();
    transactionCoordinator.pulse();
View Full Code Here

          LOG.callingJoinTransactionOnNonJtaEntityManager();
      }
      return;
    }

    final SessionImplementor session = (SessionImplementor) getSession();
    final TransactionCoordinator transactionCoordinator = session.getTransactionCoordinator();
    final TransactionImplementor transaction = transactionCoordinator.getTransaction();

    transaction.markForJoin();
    transactionCoordinator.pulse();
View Full Code Here

      final Object revision) {

        final AuditEntitiesConfiguration audEntitiesCfg = auditCfg.getAuditEntCfg();
        final String auditedEntityName = audEntitiesCfg.getAuditEntityName( entityName );
    final String revisionInfoEntityName = auditCfg.getAuditEntCfg().getRevisionInfoEntityName();
    final SessionImplementor sessionImplementor = (SessionImplementor) session;
    final Dialect dialect = sessionImplementor.getFactory().getDialect();

        // Save the audit data
        session.save(auditedEntityName, data);
        sessionCacheCleaner.scheduleAuditDataRemoval(session, data);

        // Update the end date of the previous row if this operation is expected to have a previous row
        if (getRevisionType(auditCfg, data) != RevisionType.ADD) {
      final Queryable productionEntityQueryable = getQueryable( entityName, sessionImplementor );
      final Queryable rootProductionEntityQueryable = getQueryable( productionEntityQueryable.getRootEntityName(), sessionImplementor );
      final Queryable auditedEntityQueryable = getQueryable( auditedEntityName, sessionImplementor );
      final Queryable rootAuditedEntityQueryable = getQueryable( auditedEntityQueryable.getRootEntityName(), sessionImplementor );
      final Queryable revisionInfoEntityQueryable = getQueryable( revisionInfoEntityName, sessionImplementor );

      final String updateTableName;
      if ( UnionSubclassEntityPersister.class.isInstance( rootProductionEntityQueryable ) ) {
        // this is the condition causing all the problems in terms of the generated SQL UPDATE
        // the problem being that we currently try to update the in-line view made up of the union query
        //
        // this is extremely hacky means to get the root table name for the union subclass style entities.
        // hacky because it relies on internal behavior of UnionSubclassEntityPersister
        // !!!!!! NOTICE - using subclass persister, not root !!!!!!
        updateTableName = auditedEntityQueryable.getSubclassTableName( 0 );
      }
      else {
        updateTableName = rootAuditedEntityQueryable.getTableName();
      }


      // first we need to flush the session in order to have the new audit data inserted
      // todo: expose org.hibernate.internal.SessionImpl.autoFlushIfRequired via SessionImplementor
      // for now, we duplicate some of that logic here
      autoFlushIfRequired( sessionImplementor, rootAuditedEntityQueryable, revisionInfoEntityQueryable );

      final Type revisionInfoIdType = sessionImplementor.getFactory()
          .getEntityPersister( revisionInfoEntityName )
          .getIdentifierType();
      final String revEndColumnName = rootAuditedEntityQueryable.toColumns( auditCfg.getAuditEntCfg().getRevisionEndFieldName() )[0];

      final boolean isRevisionEndTimestampEnabled = auditCfg.getAuditEntCfg().isRevisionEndTimestampEnabled();

      // update audit_ent set REVEND = ? [, REVEND_TSTMP = ?] where (prod_ent_id) = ? and REV <> ? and REVEND is null
      final Update update = new Update( dialect ).setTableName( updateTableName );
      // set REVEND = ?
      update.addColumn( revEndColumnName );
      // set [, REVEND_TSTMP = ?]
      if ( isRevisionEndTimestampEnabled ) {
        update.addColumn(
            rootAuditedEntityQueryable.toColumns(
                auditCfg.getAuditEntCfg().getRevisionEndTimestampFieldName()
            )[0]
        );
      }

      // where (prod_ent_id) = ?
      update.addPrimaryKeyColumns( rootProductionEntityQueryable.getIdentifierColumnNames() );
      // where REV <> ?
      update.addWhereColumn(
          rootAuditedEntityQueryable.toColumns(
              auditCfg.getAuditEntCfg().getRevisionNumberPath()
          )[0],
          "<> ?"
      );
      // where REVEND is null
      update.addWhereColumn( revEndColumnName, " is null" );

      // Now lets execute the sql...
      final String updateSql = update.toStatementString();

      int rowCount = session.doReturningWork(
          new ReturningWork<Integer>() {
            @Override
            public Integer execute(Connection connection) throws SQLException {
              PreparedStatement preparedStatement = connection.prepareStatement( updateSql );

              try {
                int index = 1;

                // set REVEND = ?
                final Number revisionNumber = auditCfg.getRevisionInfoNumberReader().getRevisionNumber( revision );
                revisionInfoIdType.nullSafeSet( preparedStatement, revisionNumber, index, sessionImplementor );
                index += revisionInfoIdType.getColumnSpan( sessionImplementor.getFactory() );

                // set [, REVEND_TSTMP = ?]
                if ( isRevisionEndTimestampEnabled ) {
                  final Object revEndTimestampObj = revisionTimestampGetter.get( revision );
                  final Date revisionEndTimestamp = convertRevEndTimestampToDate( revEndTimestampObj );
                  final Type revEndTsType = rootAuditedEntityQueryable.getPropertyType(
                      auditCfg.getAuditEntCfg().getRevisionEndTimestampFieldName()
                  );
                  revEndTsType.nullSafeSet( preparedStatement, revisionEndTimestamp, index, sessionImplementor );
                  index += revEndTsType.getColumnSpan( sessionImplementor.getFactory() );
                }

                // where (prod_ent_id) = ?
                final Type idType = rootProductionEntityQueryable.getIdentifierType();
                idType.nullSafeSet( preparedStatement, id, index, sessionImplementor );
                index += idType.getColumnSpan( sessionImplementor.getFactory() );

                // where REV <> ?
                final Type revType = rootAuditedEntityQueryable.getPropertyType(
                    auditCfg.getAuditEntCfg().getRevisionNumberPath()
                );
View Full Code Here

    public static Object getTargetFromProxy(SessionFactoryImplementor sessionFactoryImplementor, HibernateProxy proxy) {
        if (!proxy.getHibernateLazyInitializer().isUninitialized()) {
            return proxy.getHibernateLazyInitializer().getImplementation();
        }

        SessionImplementor sessionImplementor = proxy.getHibernateLazyInitializer().getSession();
        Session tempSession = sessionImplementor==null
        ? sessionFactoryImplementor.openTemporarySession()
        : sessionImplementor.getFactory().openTemporarySession();
        try {
      Object target = tempSession.get(
          proxy.getHibernateLazyInitializer().getEntityName(),
          proxy.getHibernateLazyInitializer().getIdentifier()
      );
View Full Code Here

    return true;
  }

  private List<X> list() {
    if (getEntityGraphQueryHint() != null) {
      SessionImplementor sessionImpl = (SessionImplementor) getEntityManager().getSession();
      HQLQueryPlan entityGraphQueryPlan = new HQLQueryPlan( getHibernateQuery().getQueryString(), false,
          sessionImpl.getEnabledFilters(), sessionImpl.getFactory(), getEntityGraphQueryHint() );
      // Safe to assume QueryImpl at this point.
      unwrap( org.hibernate.internal.QueryImpl.class ).setQueryPlan( entityGraphQueryPlan );
    }
    return query.list();
  }
View Full Code Here

   * complete.
   *
   * @param persister The persister for which to complete loading.
   */
  public void endLoadingCollections(CollectionPersister persister) {
    SessionImplementor session = getLoadContext().getPersistenceContext().getSession();
    if ( !loadContexts.hasLoadingCollectionEntries()
        && localLoadingCollectionKeys.isEmpty() ) {
      return;
    }

    // in an effort to avoid concurrent-modification-exceptions (from
    // potential recursive calls back through here as a result of the
    // eventual call to PersistentCollection#endRead), we scan the
    // internal loadingCollections map for matches and store those matches
    // in a temp collection.  the temp collection is then used to "drive"
    // the #endRead processing.
    List matches = null;
    Iterator iter = localLoadingCollectionKeys.iterator();
    while ( iter.hasNext() ) {
      final CollectionKey collectionKey = (CollectionKey) iter.next();
      final LoadingCollectionEntry lce = loadContexts.locateLoadingCollectionEntry( collectionKey );
      if ( lce == null ) {
        LOG.loadingCollectionKeyNotFound( collectionKey );
      }
      else if ( lce.getResultSet() == resultSet && lce.getPersister() == persister ) {
        if ( matches == null ) {
          matches = new ArrayList();
        }
        matches.add( lce );
        if ( lce.getCollection().getOwner() == null ) {
          session.getPersistenceContext().addUnownedCollection(
              new CollectionKey(
                  persister,
                  lce.getKey(),
                  persister.getOwnerEntityPersister().getEntityMetamodel().getEntityMode()
              ),
View Full Code Here

    if ( LOG.isDebugEnabled() ) LOG.debugf( "%s collections initialized for role: %s", count, persister.getRole() );
  }

  private void endLoadingCollection(LoadingCollectionEntry lce, CollectionPersister persister) {
    LOG.tracev( "Ending loading collection [{0}]", lce );
    final SessionImplementor session = getLoadContext().getPersistenceContext().getSession();

    boolean hasNoQueuedAdds = lce.getCollection().endRead(); // warning: can cause a recursive calls! (proxy initialization)

    if ( persister.getCollectionType().hasHolder() ) {
      getLoadContext().getPersistenceContext().addCollectionHolder( lce.getCollection() );
    }

    CollectionEntry ce = getLoadContext().getPersistenceContext().getCollectionEntry( lce.getCollection() );
    if ( ce == null ) {
      ce = getLoadContext().getPersistenceContext().addInitializedCollection( persister, lce.getCollection(), lce.getKey() );
    }
    else {
      ce.postInitialize( lce.getCollection() );
    }

    boolean addToCache = hasNoQueuedAdds && // there were no queued additions
        persister.hasCache() &&             // and the role has a cache
        session.getCacheMode().isPutEnabled() &&
        !ce.isDoremove();                   // and this is not a forced initialization during flush
    if ( addToCache ) {
      addCollectionToCache( lce, persister );
    }

    if ( LOG.isDebugEnabled() ) {
      LOG.debugf(
          "Collection fully initialized: %s",
          MessageHelper.collectionInfoString(persister, lce.getKey(), session.getFactory())
      );
    }
    if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
      session.getFactory().getStatisticsImplementor().loadCollection(persister.getRole());
    }
  }
View Full Code Here

TOP

Related Classes of org.hibernate.engine.spi.SessionImplementor

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.