Java Code Examples for org.hibernate.transform.ResultTransformer

The following examples show how to use org.hibernate.transform.ResultTransformer. 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 check out the related API usage on the sidebar.
Example 1
Source Project: ZTuoExchange_framework   Source File: TopBaseService.java    License: MIT License 6 votes vote down vote up
/**
 * 原生sql 多表关联分页查询 映射Map 或者 Class
 * @param countSql
 * @param sql
 * @param pageModel
 * @param result  映射的对象 (Map 或者 Class)
 * @return
 */
public Page createNativePageQuery(StringBuilder countSql , StringBuilder sql , PageModel pageModel,ResultTransformer result){
    Query query1 = entityManager.createNativeQuery(countSql.toString());
    long count =((BigInteger) query1.getSingleResult()).longValue() ;
    if(pageModel.getProperty()!=null && pageModel.getProperty().size()>0 && pageModel.getDirection().size() == pageModel.getProperty().size()){
        sql.append(" order by") ;
        for(int i = 0 ; i < pageModel.getProperty().size() ; i++){
            sql.append(" "+pageModel.getProperty().get(i)+" "+pageModel.getDirection().get(i)+" ");
            if(i < pageModel.getProperty().size()-1){
                sql.append(",");
            }
        }
    }
    sql.append(" limit "+pageModel.getPageSize()*(pageModel.getPageNo()-1)+" , "+pageModel.getPageSize());
    javax.persistence.Query query2 = entityManager.createNativeQuery(sql.toString());
    query2.unwrap(SQLQuery.class).setResultTransformer(result);
    List list = query2.getResultList() ;
    return new PageImpl<>(list,pageModel.getPageable(),count);
}
 
Example 2
@Override
public List<Object> getRowsFromResultSet(
		ResultSet rs,
		QueryParameters queryParameters,
		SharedSessionContractImplementor session,
		boolean returnProxies,
		ResultTransformer forcedResultTransformer,
		int maxRows,
		List<Object> hydratedObjects,
		List<EntityKey[]> subselectResultKeys) throws SQLException {
	return super.getRowsFromResultSet(
			rs,
			queryParameters,
			session,
			returnProxies,
			forcedResultTransformer,
			maxRows,
			hydratedObjects,
			subselectResultKeys
	);
}
 
Example 3
@Override
public List<Object> getRowsFromResultSet(
		ResultSet rs,
		QueryParameters queryParameters,
		SharedSessionContractImplementor session,
		boolean returnProxies,
		ResultTransformer forcedResultTransformer,
		int maxRows,
		List<Object> hydratedObjects,
		List<EntityKey[]> subselectResultKeys) throws SQLException {
	return super.getRowsFromResultSet( rs,
			queryParameters,
			session,
			returnProxies,
			forcedResultTransformer,
			maxRows,
			hydratedObjects,
			subselectResultKeys);
}
 
Example 4
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 5
default List<?> transform(QueryParameters queryParameters, QueryKey key, List<Object> result,
						  ResultTransformer resolvedTransformer) {
	if (resolvedTransformer == null) {
		return result;
	}
	else {
		CacheableResultTransformer transformer = key.getResultTransformer();
		if ( areResultSetRowsTransformedImmediately() ) {
			return transformer.retransformResults(
					result,
					getResultRowAliases(),
					queryParameters.getResultTransformer(),
					includeInResultRow()
			);
		}
		else {
			return transformer.untransformToTuples(result);
		}
	}
}
 
Example 6
protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session)
throws SQLException, HibernateException {
	final Object[] result;
	final String[] aliases;
	if ( translator.hasProjection() ) {
		Type[] types = translator.getProjectedTypes();
		result = new Object[types.length];
		String[] columnAliases = translator.getProjectedColumnAliases();
		for ( int i=0; i<result.length; i++ ) {
			result[i] = types[i].nullSafeGet(rs, columnAliases[i], session, null);
		}
		aliases = translator.getProjectedAliases();
	}
	else {
		result = row;
		aliases = userAliases;
	}
	return translator.getRootCriteria().getResultTransformer()
			.transformTuple(result, aliases);
}
 
Example 7
@Override
public List<Object> getRowsFromResultSet(
		ResultSet rs,
		QueryParameters queryParameters,
		SharedSessionContractImplementor session,
		boolean returnProxies,
		ResultTransformer forcedResultTransformer,
		int maxRows,
		List<Object> hydratedObjects,
		List<EntityKey[]> subselectResultKeys) throws SQLException {
	return super.getRowsFromResultSet( rs,
			queryParameters,
			session,
			returnProxies,
			forcedResultTransformer,
			maxRows,
			hydratedObjects,
			subselectResultKeys);
}
 
Example 8
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...
	HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(selectNewTransformer, resultTransformer, queryReturnAliases);
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = ( Object[] ) results.get( i );
			Object result = holderInstantiator.instantiate(row);
			results.set( i, result );
		}

		if(!hasSelectNew() && resultTransformer!=null) {
			return resultTransformer.transformList(results);
		} else {
			return results;
		}
	} else {
		return results;
	}
}
 
Example 9
Source Project: ZTuoExchange_framework   Source File: TopBaseService.java    License: MIT License 6 votes vote down vote up
/**
 * 原生sql 多表关联分页查询 映射Map 或者 Class
 * @param countSql
 * @param sql
 * @param pageModel
 * @param result  映射的对象 (Map 或者 Class)
 * @return
 */
public Page createNativePageQuery(StringBuilder countSql , StringBuilder sql , PageModel pageModel,ResultTransformer result){
    Query query1 = entityManager.createNativeQuery(countSql.toString());
    long count =((BigInteger) query1.getSingleResult()).longValue() ;
    if(pageModel.getProperty()!=null && pageModel.getProperty().size()>0 && pageModel.getDirection().size() == pageModel.getProperty().size()){
        sql.append(" order by") ;
        for(int i = 0 ; i < pageModel.getProperty().size() ; i++){
            sql.append(" "+pageModel.getProperty().get(i)+" "+pageModel.getDirection().get(i)+" ");
            if(i < pageModel.getProperty().size()-1){
                sql.append(",");
            }
        }
    }
    sql.append(" limit "+pageModel.getPageSize()*(pageModel.getPageNo()-1)+" , "+pageModel.getPageSize());
    javax.persistence.Query query2 = entityManager.createNativeQuery(sql.toString());
    query2.unwrap(SQLQuery.class).setResultTransformer(result);
    List list = query2.getResultList() ;
    return new PageImpl<>(list,pageModel.getPageable(),count);
}
 
Example 10
public <S> Page<S> find(String queryString, String queryCount, NamedParams params, Pageable pageable, ResultTransformer transformer) {
    Assert.hasText(queryString, "Query must has text!");
    Assert.hasText(queryCount, "Query count must has text!");
    Assert.notNull(params, "QueryParams must not be null!");
    Assert.notNull(pageable, "PageRequest must not be null!");
    Assert.notNull(transformer, "Transformer must not be null!");

    Query query = em.createQuery(queryString);

    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List<S> resultList = query.unwrap(QueryImpl.class).setResultTransformer(transformer).list();

    Query countQuery = em.createQuery(queryCount);
    setQueryParams(countQuery, params);
    Long total = (Long) countQuery.getSingleResult();

    Page<S> page = new PageImpl(resultList, pageable, total);

    return page;
}
 
Example 11
public List findBySql(StringQuery stringQuery, ResultTransformer transformer) {
    Assert.notNull(stringQuery, "StringQuery must not be null!");

    String sql = stringQuery.getQuery();
    NamedParams params = stringQuery.getParams();

    Assert.notNull(params, "NamedParams must not be null!");

    Query query = em.createNativeQuery(sql);
    setQueryParams(query, params);

    NativeQuery sqlQuery = query.unwrap(NativeQuery.class);
    stringQuery.getScalars().forEach((s, type) -> {
        sqlQuery.addScalar(s, type);
    });

    return sqlQuery.setResultTransformer(transformer).list();
}
 
Example 12
protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session)
		throws SQLException, HibernateException {
	row = toResultRow( row );
	if ( hasScalars ) {
		String[][] scalarColumns = getColumnNames();
		int queryCols = returnTypes.length;
		if ( holderClass == null && queryCols == 1 ) {
			return returnTypes[0].nullSafeGet( rs, scalarColumns[0], session, null );
		}
		else {
			row = new Object[queryCols];
			for ( int i = 0; i < queryCols; i++ )
				row[i] = returnTypes[i].nullSafeGet( rs, scalarColumns[i], session, null );
			return row;
		}
	}
	else if ( holderClass == null ) {
		return row.length == 1 ? row[0] : row;
	}
	else {
		return row;
	}

}
 
Example 13
Source Project: lams   Source File: CustomLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
public ScrollableResultsImplementor scroll(final QueryParameters queryParameters, final SharedSessionContractImplementor session)
		throws HibernateException {

	ResultTransformer resultTransformer = queryParameters.getResultTransformer();

	HolderInstantiator holderInstantiator = ( resultTransformer == null ) ?
			HolderInstantiator.NOOP_INSTANTIATOR :
			new HolderInstantiator( resultTransformer, this::getReturnAliasesForTransformer );

	return scroll(
			queryParameters,
			resultTypes,
			holderInstantiator,
			session
	);
}
 
Example 14
Source Project: lams   Source File: CustomLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...(Copy from QueryLoader)
	HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(
			null,
			resultTransformer,
			getReturnAliasesForTransformer()
	);
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = (Object[]) results.get( i );
			Object result = holderInstantiator.instantiate( row );
			results.set( i, result );
		}

		return resultTransformer.transformList( results );
	}
	else {
		return results;
	}
}
 
Example 15
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...(Copy from QueryLoader)
	HolderInstantiator holderInstantiator = HolderInstantiator.getHolderInstantiator(
			null,
			resultTransformer,
			getReturnAliasesForTransformer()
	);
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = ( Object[] ) results.get( i );
			Object result = holderInstantiator.instantiate(row);
			results.set( i, result );
		}
		
		return resultTransformer.transformList(results);
	}
	else {
		return results;
	}
}
 
Example 16
Source Project: framework   Source File: DataBaseConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param dbType
 * @return <br>
 */
@Bean
public AutoProxyBeanFactory registAutoProxyBeanFactory(final @Value("${master.db.type}") String dbType) {

    AutoProxyBeanFactory beanFactory = new AutoProxyBeanFactory();

    // dao的配置
    DaoConfig dataConfig = new DaoConfig();
    dataConfig.setCache(true);
    dataConfig.setDbType(dbType);
    dataConfig.setBaseDaoType(BaseHibernateDao.class);
    dataConfig.setCallBackType(ResultTransformer.class);
    beanFactory.setConfig(dataConfig);
    beanFactory.setInterceptors("springDaoHandler");
    beanFactory.setPackagesToScan(TransactionManagerHolder.getBasePackage());

    return beanFactory;
}
 
Example 17
Source Project: lams   Source File: QueryLoader.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
	// meant to handle dynamic instantiation queries...
	HolderInstantiator holderInstantiator = buildHolderInstantiator( resultTransformer );
	if ( holderInstantiator.isRequired() ) {
		for ( int i = 0; i < results.size(); i++ ) {
			Object[] row = (Object[]) results.get( i );
			Object result = holderInstantiator.instantiate( row );
			results.set( i, result );
		}

		if ( !hasSelectNew() && resultTransformer != null ) {
			return resultTransformer.transformList( results );
		}
		else {
			return results;
		}
	}
	else {
		return results;
	}
}
 
Example 18
@Override
public List<Object> processResultSet(ResultSet resultSet,
									 QueryParameters queryParameters,
									 SharedSessionContractImplementor session,
									 boolean returnProxies,
									 ResultTransformer forcedResultTransformer,
									 int maxRows, List<AfterLoadAction> afterLoadActions) throws SQLException {
	throw new UnsupportedOperationException( "use #reactiveProcessResultSet instead." );
}
 
Example 19
Source Project: lams   Source File: HolderInstantiator.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static ResultTransformer createSelectNewTransformer(Constructor constructor, boolean returnMaps, boolean returnLists) {
	if ( constructor != null ) {
		return new AliasToBeanConstructorResultTransformer(constructor);
	}
	else if ( returnMaps ) {
		return Transformers.ALIAS_TO_ENTITY_MAP;			
	}
	else if ( returnLists ) {
		return Transformers.TO_LIST;
	}		
	else {
		return null;
	}
}
 
Example 20
/**
 * This method is based on {@link ResultSetProcessorImpl#extractResults}
 */
@Override
@SuppressWarnings("unchecked")
public CompletionStage<List<Object>> reactiveExtractResults(
		ResultSet resultSet,
		final SharedSessionContractImplementor session,
		QueryParameters queryParameters,
		NamedParameterContext namedParameterContext,
		boolean returnProxies,
		boolean readOnly,
		ResultTransformer forcedResultTransformer,
		List<AfterLoadAction> afterLoadActionList) throws SQLException {

	handlePotentiallyEmptyCollectionRootReturns( queryParameters.getCollectionKeys(), resultSet, session );

	final ResultSetProcessingContextImpl context = createResultSetProcessingContext(
			resultSet,
			session,
			queryParameters,
			namedParameterContext,
			returnProxies,
			readOnly
	);

	final List loadResults = extractRows( resultSet, queryParameters, context );

	return CompletionStages.nullFuture()
			.thenCompose( v ->  rowReader.reactiveFinishUp( this, context, afterLoadActionList) )
			.thenApply( vv -> {
				context.wrapUp();
				return loadResults;
			});
}
 
Example 21
Source Project: lams   Source File: ConstructorNode.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public ResultTransformer getResultTransformer() {
	if ( constructor != null ) {
		return new AliasToBeanConstructorResultTransformer( constructor );
	}
	else if ( isMap ) {
		return Transformers.ALIAS_TO_ENTITY_MAP;
	}
	else if ( isList ) {
		return Transformers.TO_LIST;
	}
	throw new QueryException( "Unable to determine proper dynamic-instantiation tranformer to use." );
}
 
Example 22
@Override
public List<Object> processResultSet(ResultSet resultSet,
									 QueryParameters queryParameters,
									 SharedSessionContractImplementor session,
									 boolean returnProxies,
									 ResultTransformer forcedResultTransformer,
									 int maxRows, List<AfterLoadAction> afterLoadActions) throws SQLException {
	throw new UnsupportedOperationException( "use #reactiveProcessResultSet instead." );
}
 
Example 23
public QueryParameters(
		final Type[] positionalParameterTypes,
		final Object[] positionalParameterValues,
		final Map namedParameters,
		final Map lockModes,
		final RowSelection rowSelection,
		final boolean readOnly,
		final boolean cacheable,
		final String cacheRegion,
		//final boolean forceCacheRefresh,
		final String comment,
		final Serializable[] collectionKeys,
		ResultTransformer transformer			
) {
	this.positionalParameterTypes = positionalParameterTypes;
	this.positionalParameterValues = positionalParameterValues;
	this.namedParameters = namedParameters;
	this.lockModes = lockModes;
	this.rowSelection = rowSelection;
	this.cacheable = cacheable;
	this.cacheRegion = cacheRegion;
	//this.forceCacheRefresh = forceCacheRefresh;
	this.comment = comment;
	this.collectionKeys = collectionKeys;
	this.readOnly = readOnly;
	this.resultTransformer = transformer;
}
 
Example 24
@Override @SuppressWarnings("unchecked")
public List<Object> processResultSet(ResultSet resultSet,
									 QueryParameters queryParameters,
									 SharedSessionContractImplementor session,
									 boolean returnProxies,
									 ResultTransformer forcedResultTransformer,
									 int maxRows, List<AfterLoadAction> afterLoadActions) throws SQLException {
	throw new UnsupportedOperationException( "use #reactiveProcessResultSet instead." );
}
 
Example 25
public QueryParameters(
	final Type[] positionalParameterTypes,
	final Object[] positionalParameterValues,
	final Map namedParameters,
	final Map lockModes,
	final RowSelection rowSelection,
	final boolean readOnly,
	final boolean cacheable,
	final String cacheRegion,
	//final boolean forceCacheRefresh,
	final String comment,
	final Serializable[] collectionKeys,
	final Object optionalObject,
	final String optionalEntityName,
	final Serializable optionalId,
	final ResultTransformer transformer
) {
	this(
		positionalParameterTypes, 
		positionalParameterValues, 
		namedParameters, 
		lockModes, 
		rowSelection, 
		readOnly, 
		cacheable, 
		cacheRegion,
		comment,
		collectionKeys,
		transformer
	);
	this.optionalEntityName = optionalEntityName;
	this.optionalId = optionalId;
	this.optionalObject = optionalObject;
}
 
Example 26
public ReactiveQueryLoader(
		QueryTranslatorImpl queryTranslator,
		SessionFactoryImplementor factory,
		SelectClause selectClause) {
	super( queryTranslator, factory, selectClause );
	this.queryTranslator = queryTranslator;
	this.factory = factory;
	this.selectClause = selectClause;
	this.resultSetProcessor = new ReactiveLoaderBasedResultSetProcessor( this ) {
		public CompletionStage<List<Object>> reactiveExtractResults(ResultSet rs,
																	SharedSessionContractImplementor session,
																	QueryParameters queryParameters,
																	NamedParameterContext namedParameterContext,
																	boolean returnProxies, boolean readOnly,
																	ResultTransformer forcedResultTransformer,
																	List<AfterLoadAction> afterLoadActionList) throws SQLException {
			final RowSelection rowSelection = queryParameters.getRowSelection();
			final ResultSet resultSetPreprocessed = preprocessResultSet(
					rs,
					rowSelection,
					getLimitHandler( rowSelection ),
					false,
					session
			);
			return super.reactiveExtractResults(
					resultSetPreprocessed,
					session,
					queryParameters,
					namedParameterContext,
					returnProxies,
					readOnly,
					forcedResultTransformer,
					afterLoadActionList
			);
		}
	};
}
 
Example 27
@Override
public List<Object> processResultSet(ResultSet resultSet,
									 QueryParameters queryParameters,
									 SharedSessionContractImplementor session,
									 boolean returnProxies,
									 ResultTransformer forcedResultTransformer,
									 int maxRows, List<AfterLoadAction> afterLoadActions) throws SQLException {
	throw new UnsupportedOperationException( "use #reactiveProcessResultSet instead." );
}
 
Example 28
CompletionStage<List<Object>> reactiveExtractResults(
ResultSet resultSet,
final SharedSessionContractImplementor session,
QueryParameters queryParameters,
NamedParameterContext namedParameterContext,
boolean returnProxies,
boolean readOnly,
ResultTransformer forcedResultTransformer,
List<AfterLoadAction> afterLoadActionList) throws SQLException;
 
Example 29
public HolderInstantiator( 
		ResultTransformer transformer,
		String[] queryReturnAliases
) {
	this.transformer = transformer;		
	this.queryReturnAliases = queryReturnAliases;
}
 
Example 30
Source Project: lams   Source File: QueryTranslatorImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) {
	return HolderInstantiator.resolveClassicResultTransformer(
			holderConstructor,
			resultTransformer
	);
}