Java Code Examples for org.hibernate.engine.spi.SessionImplementor

The following examples show how to use org.hibernate.engine.spi.SessionImplementor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
private CompletionStage<List<Object>> performOrderedBatchLoad(
		List<Serializable> idsInBatch,
		LockOptions lockOptions,
		OuterJoinLoadable persister,
		SessionImplementor session) {
	final int batchSize =  idsInBatch.size();
	final ReactiveDynamicBatchingEntityLoader batchingLoader = new ReactiveDynamicBatchingEntityLoader(
			persister,
			batchSize,
			lockOptions,
			session.getFactory(),
			session.getLoadQueryInfluencers()
	);

	final Serializable[] idsInBatchArray = idsInBatch.toArray(new Serializable[0]);
	QueryParameters qp = buildMultiLoadQueryParameters( persister, idsInBatchArray, lockOptions );
	CompletionStage<List<Object>> result = batchingLoader.doEntityBatchFetch(session, qp, idsInBatchArray);
	idsInBatch.clear();
	return result;
}
 
Example 2
default CompletionStage<List<Object>> doReactiveList(
		final String sql, final String queryIdentifier,
		final SessionImplementor session,
		final QueryParameters queryParameters,
		final ResultTransformer forcedResultTransformer)
		throws HibernateException {

	final StatisticsImplementor statistics = session.getSessionFactory().getStatistics();
	final boolean stats = statistics.isStatisticsEnabled();
	final long startTime = stats ? System.nanoTime() : 0;

	return doReactiveQueryAndInitializeNonLazyCollections( sql, session, queryParameters, true, forcedResultTransformer )
			.handle( (list, err) -> {
				CompletionStages.logSqlException( err, () -> "could not execute query", sql );

				if ( err ==null && stats ) {
					final long endTime = System.nanoTime();
					final long milliseconds = TimeUnit.MILLISECONDS.convert( endTime - startTime, TimeUnit.NANOSECONDS );
					statistics.queryExecuted( queryIdentifier, list.size(), milliseconds );
				}

				return CompletionStages.returnOrRethrow(err, list );
			} );
}
 
Example 3
private boolean updated(FlushEntityEvent event) {
    final EntityEntry entry = event.getEntityEntry();
    final Object entity = event.getEntity();

    int[] dirtyProperties;
    EntityPersister persister = entry.getPersister();
    final Object[] values = event.getPropertyValues();
    SessionImplementor session = event.getSession();

    if ( event.hasDatabaseSnapshot() ) {
        dirtyProperties = persister.findModified( event.getDatabaseSnapshot(), values, entity, session );
    }
    else {
        dirtyProperties = persister.findDirty( values, entry.getLoadedState(), entity, session );
    }

    return dirtyProperties != null;
}
 
Example 4
private Object[] getValues(Object entity, EntityEntry entry, boolean mightBeDirty, SessionImplementor session) {
	final Object[] loadedState = entry.getLoadedState();
	final Status status = entry.getStatus();
	final EntityPersister persister = entry.getPersister();

	final Object[] values;
	if ( status == Status.DELETED ) {
		//grab its state saved at deletion
		values = entry.getDeletedState();
	}
	else if ( !mightBeDirty && loadedState != null ) {
		values = loadedState;
	}
	else {
		checkId( entity, persister, entry.getId(), session );

		// grab its current state
		values = persister.getPropertyValues( entity );

		checkNaturalId( persister, entry, values, loadedState, session );
	}
	return values;
}
 
Example 5
Source Project: unitime   Source File: BlobRoomAvailabilityService.java    License: Apache License 2.0 6 votes vote down vote up
protected Document receiveResponse() throws IOException, DocumentException {
    try {
        SessionImplementor session = (SessionImplementor)new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        String response = null;
        try {
            CallableStatement call = connection.prepareCall(iResponseSql);
            call.registerOutParameter(1, java.sql.Types.CLOB);
            call.execute();
            response = call.getString(1);
            call.close();
        } finally {
        	session.getJdbcConnectionAccess().releaseConnection(connection);
        }
        if (response==null || response.length()==0) return null;
        StringReader reader = new StringReader(response);
        Document document = (new SAXReader()).read(reader);
        reader.close();
        return document;
    } catch (Exception e) {
        sLog.error("Unable to receive response: "+e.getMessage(),e);
        return null;
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}
 
Example 6
Source Project: hibernate-types   Source File: PostgreSQLRangeType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return Range.integerRange(value);
    } else if("int8range".equals(type)) {
        return Range.longRange(value);
    } else if("numrange".equals(type)) {
        return Range.bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example 7
/**
 * Is this instance persistent or detached?
 * <p/>
 * If <tt>assumed</tt> is non-null, don't hit the database to make the determination, instead assume that
 * value; the client code must be prepared to "recover" in the case that this assumed result is incorrect.
 *
 * @param entityName The name of the entity
 * @param entity The entity instance
 * @param assumed The assumed return value, if avoiding database hit is desired
 * @param session The session
 *
 * @return {@code true} if the given entity is not transient (meaning it is either detached/persistent)
 */
@SuppressWarnings("SimplifiableIfStatement")
public static CompletionStage<Boolean> isNotTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session) {
	if ( entity instanceof HibernateProxy ) {
		return CompletionStages.trueFuture();
	}

	if ( session.getPersistenceContextInternal().isEntryFor( entity ) ) {
		return CompletionStages.trueFuture();
	}

	// todo : shouldnt assumed be revered here?

	return isTransient( entityName, entity, assumed, session )
			.thenApply( trans -> !trans );
}
 
Example 8
/**
 * Perform any property value substitution that is necessary
 * (interceptor callback, version initialization...)
 *
 * @param entity The entity
 * @param id The entity identifier
 * @param values The snapshot entity state
 * @param persister The entity persister
 * @param source The originating session
 *
 * @return True if the snapshot state changed such that
 *         reinjection of the values into the entity is required.
 */
protected boolean substituteValuesIfNecessary(
		Object entity,
		Serializable id,
		Object[] values,
		EntityPersister persister,
		SessionImplementor source) {
	boolean substitute = source.getInterceptor().onSave(
			entity,
			id,
			values,
			persister.getPropertyNames(),
			persister.getPropertyTypes()
	);

	//keep the existing version number in the case of replicate!
	if ( persister.isVersioned() ) {
		substitute = Versioning.seedVersion(
				values,
				persister.getVersionProperty(),
				persister.getVersionType(),
				source
		) || substitute;
	}
	return substitute;
}
 
Example 9
Source Project: es   Source File: CollectionToStringUserType.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 从JDBC ResultSet读取数据,将其转换为自定义类型后返回
 * (此方法要求对克能出现null值进行处理)
 * names中包含了当前自定义类型的映射字段名称
 *
 * @param names
 * @param owner
 * @return
 * @throws org.hibernate.HibernateException
 * @throws java.sql.SQLException
 */
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
    String valueStr = rs.getString(names[0]);
    if (StringUtils.isEmpty(valueStr)) {
        return newCollection();
    }

    String[] values = StringUtils.split(valueStr, separator);

    Collection result = newCollection();

    for (String value : values) {
        if(StringUtils.isNotEmpty(value)) {
            result.add(ConvertUtils.convert(value, elementType));
        }
    }
    return result;

}
 
Example 10
Source Project: hibernate-types   Source File: PostgreSQLGuavaRangeType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Range get(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
    PGobject pgObject = (PGobject) rs.getObject(names[0]);

    if (pgObject == null) {
        return null;
    }

    String type = pgObject.getType();
    String value = pgObject.getValue();

    if("int4range".equals(type)) {
        return integerRange(value);
    } else if("int8range".equals(type)) {
        return longRange(value);
    } else if("numrange".equals(type)) {
        return bigDecimalRange(value);
    } else {
        throw new IllegalStateException("The range type [" + type + "] is not supported!");
    }
}
 
Example 11
/**
 * Deerialize a {@link UnresolvedEntityInsertActions} object.
 *
 * @param ois - the input stream.
 * @param session - the session.
 *
 * @return the deserialized  {@link UnresolvedEntityInsertActions} object
 * @throws IOException if there is an error writing this object to the output stream.
 * @throws ClassNotFoundException if there is a class that cannot be loaded.
 */
public static UnresolvedEntityInsertActions deserialize(
		ObjectInputStream ois,
		SessionImplementor session) throws IOException, ClassNotFoundException {

	final UnresolvedEntityInsertActions rtn = new UnresolvedEntityInsertActions();

	final int queueSize = ois.readInt();
	LOG.tracev( "Starting deserialization of [{0}] unresolved insert entries", queueSize );
	for ( int i = 0; i < queueSize; i++ ) {
		final AbstractEntityInsertAction unresolvedAction = (AbstractEntityInsertAction) ois.readObject();
		unresolvedAction.afterDeserialize( session );
		rtn.addUnresolvedEntityInsertAction(
				unresolvedAction,
				unresolvedAction.findNonNullableTransientEntities()
		);
	}
	return rtn;
}
 
Example 12
/**
 * Attempts to load the entity from the second-level cache.
 *
 * @param event The load event
 * @param persister The persister for the entity being requested for load
 *
 * @return The entity from the second-level cache, or null.
 */
private Object loadFromSecondLevelCache(
		final LoadEvent event,
		final EntityPersister persister,
		final EntityKey entityKey) {

	final SessionImplementor source = event.getSession();
	final boolean useCache = persister.canReadFromCache()
			&& source.getCacheMode().isGetEnabled()
			&& event.getLockMode().lessThan( LockMode.READ );

	if ( !useCache ) {
		// we can't use cache here
		return null;
	}

	final Object ce = getFromSharedCache( event, persister, source );

	if ( ce == null ) {
		// nothing was found in cache
		return null;
	}

	return processCachedEntry( event, persister, ce, source, entityKey );
}
 
Example 13
Source Project: spring-analysis-note   Source File: HibernateTransactionManager.java    License: MIT License 5 votes vote down vote up
/**
 * Return whether the given Hibernate Session will always hold the same
 * JDBC Connection. This is used to check whether the transaction manager
 * can safely prepare and clean up the JDBC Connection used for a transaction.
 * <p>The default implementation checks the Session's connection release mode
 * to be "on_close".
 * @param session the Hibernate Session to check
 * @see ConnectionReleaseMode#ON_CLOSE
 */
@SuppressWarnings("deprecation")
protected boolean isSameConnectionForEntireSession(Session session) {
	if (!(session instanceof SessionImplementor)) {
		// The best we can do is to assume we're safe.
		return true;
	}
	ConnectionReleaseMode releaseMode =
			((SessionImplementor) session).getJdbcCoordinator().getConnectionReleaseMode();
	return ConnectionReleaseMode.ON_CLOSE.equals(releaseMode);
}
 
Example 14
Source Project: HibernateDemos   Source File: SpatialDemo.java    License: The Unlicense 5 votes vote down vote up
private Session openSession() throws Exception {
	final Session s = sessionFactory.openSession();
	final SessionImplementor sImpl = (SessionImplementor) s;
	// init GeoDB H2 extension
	GeoDB.InitGeoDB( sImpl.connection() );
	return s;
}
 
Example 15
Source Project: hibernate-demos   Source File: MultiTenancyDemo.java    License: Apache License 2.0 5 votes vote down vote up
private static void createTable(String tenantId) {
	// Multi-tenancy does not currently support schema export, so manually create it here.
	try {
		final Session s = openSession( tenantId );
		final SessionImplementor sImpl = (SessionImplementor) s;
		final Connection conn = sImpl.connection();
		final Statement stmt = conn.createStatement();
		stmt.executeUpdate( "CREATE TABLE Project (id bigint generated by default as identity, name varchar(255), primary key (id))" );
		stmt.close();
		s.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 16
Source Project: unitime   Source File: XmlClobType.java    License: Apache License 2.0 5 votes vote down vote up
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException {
      Clob clob = rs.getClob(names[0]);
      if (clob==null) return null;
try {
	SAXReader reader = new SAXReader();
	Document document = reader.read(clob.getCharacterStream());
	return document;
} catch (DocumentException e) {
	throw new HibernateException(e.getMessage(),e);
}
  }
 
Example 17
@Override
public boolean putFromLoad(SessionImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
        throws CacheException {
    if (minimalPutOverride && region.contains(key)) {
        return false;
    }

    region.put(session, key, value);
    return true;
}
 
Example 18
Source Project: hibernate-types   Source File: SQLExtractor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the underlying SQL generated by the provided JPA query.
 *
 * @param query JPA query
 * @return the underlying SQL generated by the provided JPA query
 */
public static String from(Query query) {
    AbstractQueryImpl abstractQuery = query.unwrap(AbstractQueryImpl.class);
    SessionImplementor session = ReflectionUtils.getFieldValue(abstractQuery, "session");
    String[] sqls = session.getFactory()
        .getQueryPlanCache()
        .getHQLQueryPlan(abstractQuery.getQueryString(), false, Collections.<String, Filter>emptyMap())
        .getSqlStrings();

    return sqls.length > 0 ? sqls[0] : null;
}
 
Example 19
Source Project: hibernate-types   Source File: PostgreSQLGuavaRangeType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void set(PreparedStatement st, Range range, int index, SessionImplementor session) throws SQLException {

    if (range == null) {
        st.setNull(index, Types.OTHER);
    } else {
        PGobject object = new PGobject();
        object.setType(determineRangeType(range));
        object.setValue(asString(range));

        st.setObject(index, object);
    }
}
 
Example 20
/**
 * Return the identifier of the persistent or transient object, or throw
 * an exception if the instance is "unsaved"
 * <p/>
 * Used by OneToOneType and ManyToOneType to determine what id value should
 * be used for an object that may or may not be associated with the session.
 * This does a "best guess" using any/all info available to use (not just the
 * EntityEntry).
 *
 * @param entityName The name of the entity
 * @param object The entity instance
 * @param session The session
 *
 * @return The identifier
 *
 * @throws TransientObjectException if the entity is transient (does not yet have an identifier)
 */
public static CompletionStage<Serializable> getEntityIdentifierIfNotUnsaved(
		final String entityName,
		final Object object,
		final SessionImplementor session) throws TransientObjectException {
	if ( object == null ) {
		return CompletionStages.nullFuture();
	}
	else {
		Serializable id = session.getContextEntityIdentifier( object );
		if ( id == null ) {
			// context-entity-identifier returns null explicitly if the entity
			// is not associated with the persistence context; so make some
			// deeper checks...
			return isTransient( entityName, object, Boolean.FALSE, session )
					.thenApply( trans -> {
						if ( trans ) {
							throw new TransientObjectException(
									"object references an unsaved transient instance - save the transient instance before flushing: " +
											(entityName == null ? session.guessEntityName( object ) : entityName)
							);
						}
						return session.getEntityPersister( entityName, object )
								.getIdentifier( object, session );
					} );
		}
		else {
			return CompletionStages.completedFuture( id );
		}
	}
}
 
Example 21
@Override
public boolean putFromLoad(SessionImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
        throws CacheException {
    if (minimalPutOverride && region.contains(key)) {
        return false;
    }

    region.put(session, key, value);
    return true;
}
 
Example 22
/** {@inheritDoc} */
@Override public boolean putFromLoad(SessionImplementor ses, Object key, Object val, long txTs, Object ver, boolean minimalPutOverride)
    throws CacheException {
    stgy.putFromLoad(key, val, minimalPutOverride);

    return true;
}
 
Example 23
@Override
public Object get(ResultSet rs, String name, SessionImplementor implementor) throws SQLException {
    Object result = super.get(rs, name, implementor);

    // in the past includes and excludes patterns
    // were stored as String[]
    if (result instanceof String[]) {
        return ImmutableSet.copyOf((String[]) result);
    }

    return result;
}
 
Example 24
Source Project: jasypt   Source File: EncryptedBigIntegerType.java    License: Apache License 2.0 5 votes vote down vote up
public void nullSafeSet(final PreparedStatement st, final Object value, final int index,
        final SessionImplementor session)
        throws HibernateException, SQLException {
    checkInitialization();
    if (value == null) {
        st.setNull(index, sqlType);
    } else {
        final BigInteger encryptedMessage = 
            this.encryptor.encrypt((BigInteger) value);
        st.setBigDecimal(index, new BigDecimal(encryptedMessage));
    }
}
 
Example 25
Source Project: jasypt   Source File: EncryptedBigDecimalType.java    License: Apache License 2.0 5 votes vote down vote up
public void nullSafeSet(final PreparedStatement st, final Object value, final int index,
        final SessionImplementor session)
        throws HibernateException, SQLException {
    checkInitialization();
    if (value == null) {
        st.setNull(index, sqlType);
    } else {
        final BigDecimal scaledValue = 
            ((BigDecimal) value).setScale(
                    this.decimalScale.intValue(), BigDecimal.ROUND_DOWN);
        final BigDecimal encryptedMessage = 
            this.encryptor.encrypt(scaledValue);
        st.setBigDecimal(index, encryptedMessage);
    }
}
 
Example 26
Source Project: sakai   Source File: EnumUserType.java    License: Educational Community License v2.0 5 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet resultSet, String[] strings, SessionImplementor sessionImplementor, Object o) throws HibernateException, SQLException {
    String name = resultSet.getString(strings[0]);
    E result = null;

    if (!resultSet.wasNull())
    {
        result = Enum.valueOf(myClass, name);
    }

    return result;
}
 
Example 27
Source Project: jasypt   Source File: AbstractEncryptedAsStringType.java    License: Apache License 2.0 5 votes vote down vote up
public void nullSafeSet(final PreparedStatement st, final Object value, final int index,
        final SessionImplementor session) throws HibernateException, SQLException {

    checkInitialization();
    if (value == null) {
        st.setNull(index, sqlType);
    } else {
        st.setString(index, this.encryptor.encrypt(convertToString(value)));
    }
    
}
 
Example 28
@Override
public RuntimeException mapManagedFlushFailure(String message, RuntimeException failure, SessionImplementor session) {
	if ( HibernateException.class.isInstance( failure ) ) {
		throw session.getExceptionConverter().convert( failure );
	}
	if ( PersistenceException.class.isInstance( failure ) ) {
		throw failure;
	}
	throw new PersistenceException( message, failure );
}
 
Example 29
Source Project: hibernate-types   Source File: PostgreSQLRangeType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void set(PreparedStatement st, Range range, int index, SessionImplementor session) throws SQLException {

    if (range == null) {
        st.setNull(index, Types.OTHER);
    } else {
        PGobject object = new PGobject();
        object.setType(determineRangeType(range));
        object.setValue(range.asString());

        st.setObject(index, object);
    }
}
 
Example 30
Source Project: flux   Source File: ListJsonType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
    String value = rs.getString(names[0]);

    if (value == null) {
        return new LinkedList<String>();
    }

    try {
        return deSerialize(value);
    } catch (IOException e) {
        throw new SQLException("Cannot deserialize json string " + value + ". Exception " + e.getMessage());
    }
}