Package org.hibernate.engine.spi

Examples of org.hibernate.engine.spi.SessionImplementor


    return INVOKE_IMPLEMENTATION;

  }

  private Object getReplacement() {
    final SessionImplementor session = getSession();
    if ( isUninitialized() && session != null && session.isOpen()) {
      final EntityKey key = session.generateEntityKey(
          getIdentifier(),
          session.getFactory().getEntityPersister( getEntityName() )
      );
      final Object entity = session.getPersistenceContext().getEntity(key);
      if (entity!=null) setImplementation( entity );
    }

    if ( isUninitialized() ) {
      if (replacement==null) {
View Full Code Here


        throw new LazyInitializationException( "could not initialize proxy - no Session" );
      }
      try {
        SessionFactoryImplementor sf = (SessionFactoryImplementor)
            SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid );
        SessionImplementor session = (SessionImplementor) sf.openSession();
       
        // TODO: On the next major release, add an
        // 'isJTA' or 'getTransactionFactory' method to Session.
        boolean isJTA = session.getTransactionCoordinator()
            .getTransactionContext().getTransactionEnvironment()
            .getTransactionFactory()
            .compatibleWithJtaSynchronization();
       
        if ( !isJTA ) {
          // Explicitly handle the transactions only if we're not in
          // a JTA environment.  A lazy loading temporary session can
          // be created even if a current session and transaction are
          // open (ex: session.clear() was used).  We must prevent
          // multiple transactions.
          ( ( Session) session ).beginTransaction();
        }

        try {
          target = session.immediateLoad( entityName, id );
        }
        finally {
          // make sure the just opened temp session gets closed!
          try {
            if ( !isJTA ) {
              ( ( Session) session ).getTransaction().commit();
            }
            ( (Session) session ).close();
          }
          catch (Exception e) {
            log.warn( "Unable to close temporary session used to load lazy proxy associated to no session" );
          }
        }
        initialized = true;
        checkTargetState();
      }
      catch (Exception e) {
        e.printStackTrace();
        throw new LazyInitializationException( e.getMessage() );
      }
    }
    else if ( session.isOpen() && session.isConnected() ) {
      target = session.immediateLoad( entityName, id );
      initialized = true;
      checkTargetState();
    }
    else {
      throw new LazyInitializationException( "could not initialize proxy - Session was closed or disced" );
View Full Code Here

        log.tracef( "No object to initialize", maxResults );
      }
      return;
    }

    SessionImplementor sessionImplementor = (SessionImplementor) session;
    String entityName = session.getSessionFactory().getClassMetadata( entityType ).getEntityName();
    EntityPersister persister = sessionImplementor.getFactory().getEntityPersister( entityName );
    PersistenceContext persistenceContext = sessionImplementor.getPersistenceContext();

    //check the persistence context
    List<EntityInfo> remainingEntityInfos = new ArrayList<EntityInfo>( maxResults );
    for ( EntityInfo entityInfo : entityInfos ) {
      if ( ObjectLoaderHelper.areDocIdAndEntityIdIdentical( entityInfo, session ) ) {
        EntityKey entityKey = sessionImplementor.generateEntityKey( entityInfo.getId(), persister );
        final boolean isInitialized = persistenceContext.containsEntity( entityKey );
        if ( !isInitialized ) {
          remainingEntityInfos.add( entityInfo );
        }
      }
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 = sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().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()
                );
                revType.nullSafeSet( preparedStatement, revisionNumber, index, sessionImplementor );

                // where REVEND is null
                //     nothing to bind....

                return sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( preparedStatement );
              }
              finally {
                sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().release( preparedStatement );
              }
            }
          }
      );
View Full Code Here

      else if ( Tuple.class.equals( resultClass ) ) {
        TupleBuilderTransformer tupleTransformer = new TupleBuilderTransformer( hqlQuery );
        hqlQuery.setResultTransformer( tupleTransformer  );
      }
      else {
        final SessionImplementor session = unwrap( SessionImplementor.class );
        final HQLQueryPlan queryPlan = session.getFactory().getQueryPlanCache().getHQLQueryPlan(
            jpaqlString,
            false,
            session.getLoadQueryInfluencers().getEnabledFilters()
        );
        final Class dynamicInstantiationClass = queryPlan.getDynamicInstantiationResultType();
        if ( dynamicInstantiationClass != null ) {
          if ( ! resultClass.isAssignableFrom( dynamicInstantiationClass ) ) {
            throw new IllegalArgumentException(
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

    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 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 ) {
      // see if the custom dirtiness strategy can tell us...
      class DirtyCheckContextImpl implements CustomEntityDirtinessStrategy.DirtyCheckContext {
        int[] found = null;
        @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
      );
View Full Code Here

  @Override
  public void execute() throws HibernateException {
    nullifyTransientReferencesIfNotAlready();

    EntityPersister persister = getPersister();
    SessionImplementor session = getSession();
    Object instance = getInstance();
    Serializable id = getId();

    boolean veto = preInsert();

    // Don't need to lock the cache here, since if someone
    // else inserted the same pk first, the insert would fail

    if ( !veto ) {
     
      persister.insert( id, getState(), instance, session );
   
      EntityEntry entry = session.getPersistenceContext().getEntry( instance );
      if ( entry == null ) {
        throw new AssertionFailure( "possible nonthreadsafe access to session" );
      }
     
      entry.postInsert();
 
      if ( persister.hasInsertGeneratedProperties() ) {
        persister.processInsertGeneratedProperties( id, instance, getState(), session );
        if ( persister.isVersionPropertyGenerated() ) {
          version = Versioning.getVersion( getState(), persister );
        }
        entry.postUpdate(instance, getState(), version);
      }

      getSession().getPersistenceContext().registerInsertedKey( getPersister(), getId() );
    }

    final SessionFactoryImplementor factory = getSession().getFactory();

    if ( isCachePutEnabled( persister, session ) ) {
     
      CacheEntry ce = new CacheEntry(
          getState(),
          persister,
          persister.hasUninitializedLazyProperties( instance ),
          version,
          session,
          instance
        );
     
      cacheEntry = persister.getCacheEntryStructure().structure(ce);
      final CacheKey ck = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() );
      boolean put = persister.getCacheAccessStrategy().insert( ck, cacheEntry, version );
     
      if ( put && factory.getStatistics().isStatisticsEnabled() ) {
        factory.getStatisticsImplementor().secondLevelCachePut( getPersister().getCacheAccessStrategy().getRegion().getName() );
      }
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.