org.hibernate.engine.spi.SessionImplementor Java Examples

The following examples show how to use org.hibernate.engine.spi.SessionImplementor. 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 check out the related API usage on the sidebar.
Example #1
Source File: DefaultLoadEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: PostgreSQLRangeType.java    From hibernate-types with 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 #3
Source File: CollectionToStringUserType.java    From es with 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 #4
Source File: BlobRoomAvailabilityService.java    From unitime with 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 #5
Source File: AbstractReactiveSaveEventListener.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #6
Source File: ForeignKeys.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #7
Source File: DefaultFlushEntityEventListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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 #8
Source File: OptimisticLockingChildUpdatesRootVersionTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: CachingReactiveLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #10
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with 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
Source File: UnresolvedEntityInsertActions.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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
Source File: ReactiveDynamicBatchingEntityLoaderBuilder.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 #13
Source File: MultiTenancyDemo.java    From hibernate-demos with 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 #14
Source File: NonStrictReadWriteEntityRegionAccessStrategy.java    From redisson with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: XmlClobType.java    From unitime with 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 #16
Source File: ForeignKeys.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #17
Source File: TransactionalEntityRegionAccessStrategy.java    From redisson with Apache License 2.0 5 votes vote down vote up
@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 File: HibernateAbstractRegionAccessStrategy.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@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 #19
Source File: SpatialDemo.java    From HibernateDemos with 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 #20
Source File: PostgreSQLGuavaRangeType.java    From hibernate-types with 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 #21
Source File: PatternType.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #22
Source File: EncryptedBigIntegerType.java    From jasypt with 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 #23
Source File: EncryptedBigDecimalType.java    From jasypt with 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 #24
Source File: EnumUserType.java    From sakai with 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 #25
Source File: AbstractEncryptedAsStringType.java    From jasypt with 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 #26
Source File: ExceptionMapperLegacyJpaImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #27
Source File: PostgreSQLRangeType.java    From hibernate-types with 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 #28
Source File: ListJsonType.java    From flux with 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());
    }
}
 
Example #29
Source File: NonStrictReadWriteCollectionRegionAccessStrategy.java    From redisson with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: TransactionalCollectionRegionAccessStrategy.java    From redisson with Apache License 2.0 5 votes vote down vote up
@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;
}