org.hibernate.internal.util.StringHelper Java Examples

The following examples show how to use org.hibernate.internal.util.StringHelper. 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: AbstractLoadPlanBuildingAssociationVisitationStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void finishingCollection(CollectionDefinition collectionDefinition) {
	final boolean isRoot = fetchSourceStack.isEmpty() && collectionReferenceStack.size() == 1;
	if ( !isRoot ) {
		// if not, this call should represent a fetch which will be handled in #finishingAttribute
		return;
	}

	final CollectionReference popped = popFromCollectionStack();
	checkedPoppedCollection( popped, collectionDefinition );

	log.tracef(
			"%s Finished root collection : %s",
			StringHelper.repeat( "<<", fetchSourceStack.size() ),
			collectionDefinition.getCollectionPersister().getRole()
	);
}
 
Example #2
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void bindDiscriminatorValue() {
	if ( StringHelper.isEmpty( discriminatorValue ) ) {
		Value discriminator = persistentClass.getDiscriminator();
		if ( discriminator == null ) {
			persistentClass.setDiscriminatorValue( name );
		}
		else if ( "character".equals( discriminator.getType().getName() ) ) {
			throw new AnnotationException(
					"Using default @DiscriminatorValue for a discriminator of type CHAR is not safe"
			);
		}
		else if ( "integer".equals( discriminator.getType().getName() ) ) {
			persistentClass.setDiscriminatorValue( String.valueOf( name.hashCode() ) );
		}
		else {
			persistentClass.setDiscriminatorValue( name ); //Spec compliant
		}
	}
	else {
		//persistentClass.getDiscriminator()
		persistentClass.setDiscriminatorValue( discriminatorValue );
	}
}
 
Example #3
Source File: NamedProcedureCallDefinition.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
ParameterDefinitions(StoredProcedureParameter[] parameters, Map<String, Object> queryHintMap) {
	if ( parameters == null || parameters.length == 0 ) {
		parameterStrategy = ParameterStrategy.POSITIONAL;
		parameterDefinitions = new ParameterDefinition[0];
	}
	else {
		parameterStrategy = StringHelper.isNotEmpty( parameters[0].name() )
				? ParameterStrategy.NAMED
				: ParameterStrategy.POSITIONAL;
		parameterDefinitions = new ParameterDefinition[ parameters.length ];

		for ( int i = 0; i < parameters.length; i++ ) {
			parameterDefinitions[i] = ParameterDefinition.from(
					parameterStrategy,
					parameters[i],
					// i+1 for the position because the apis say the numbers are 1-based, not zero
					i+1,
					queryHintMap
			);
		}
	}
}
 
Example #4
Source File: CriteriaBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Package-protected method to centralize checking of criteria query multi-selects as defined by the
 * {@link CriteriaQuery#multiselect(List)}  method.
 *
 * @param selections The selection varargs to check
 *
 * @throws IllegalArgumentException If the selection items are not valid per {@link CriteriaQuery#multiselect}
 * documentation.
 * <i>&quot;An argument to the multiselect method must not be a tuple-
    * or array-valued compound selection item.&quot;</i>
 */
void checkMultiselect(List<Selection<?>> selections) {
	final HashSet<String> aliases = new HashSet<String>( CollectionHelper.determineProperSizing( selections.size() ) );

	for ( Selection<?> selection : selections ) {
		if ( selection.isCompoundSelection() ) {
			if ( selection.getJavaType().isArray() ) {
				throw new IllegalArgumentException(
						"Selection items in a multi-select cannot contain compound array-valued elements"
				);
			}
			if ( Tuple.class.isAssignableFrom( selection.getJavaType() ) ) {
				throw new IllegalArgumentException(
						"Selection items in a multi-select cannot contain compound tuple-valued elements"
				);
			}
		}
		if ( StringHelper.isNotEmpty( selection.getAlias() ) ) {
			boolean added = aliases.add( selection.getAlias() );
			if ( ! added ) {
				throw new IllegalArgumentException( "Multi-select expressions defined duplicate alias : " + selection.getAlias() );
			}
		}
	}
}
 
Example #5
Source File: WhereParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void preprocess(String token, QueryTranslatorImpl q) throws QueryException {
	// ugly hack for cases like "elements(foo.bar.collection)"
	// (multi-part path expression ending in elements or indices)
	String[] tokens = StringHelper.split( ".", token, true );
	if (
			tokens.length > 5 &&
			( CollectionPropertyNames.COLLECTION_ELEMENTS.equals( tokens[tokens.length - 1] )
			|| CollectionPropertyNames.COLLECTION_INDICES.equals( tokens[tokens.length - 1] ) )
	) {
		pathExpressionParser.start( q );
		for ( int i = 0; i < tokens.length - 3; i++ ) {
			pathExpressionParser.token( tokens[i], q );
		}
		pathExpressionParser.token( null, q );
		pathExpressionParser.end( q );
		addJoin( pathExpressionParser.getWhereJoin(), q );
		pathExpressionParser.ignoreInitialJoin();
	}
}
 
Example #6
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void setFKNameIfDefined(Join join) {
	// just awful..

	org.hibernate.annotations.Table matchingTable = findMatchingComplimentTableAnnotation( join );
	if ( matchingTable != null && !BinderHelper.isEmptyAnnotationValue( matchingTable.foreignKey().name() ) ) {
		( (SimpleValue) join.getKey() ).setForeignKeyName( matchingTable.foreignKey().name() );
	}
	else {
		javax.persistence.SecondaryTable jpaSecondaryTable = findMatchingSecondaryTable( join );
		if ( jpaSecondaryTable != null ) {
			if ( jpaSecondaryTable.foreignKey().value() == ConstraintMode.NO_CONSTRAINT ) {
				( (SimpleValue) join.getKey() ).setForeignKeyName( "none" );
			}
			else {
				( (SimpleValue) join.getKey() ).setForeignKeyName( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().name() ) );
				( (SimpleValue) join.getKey() ).setForeignKeyDefinition( StringHelper.nullIfEmpty( jpaSecondaryTable.foreignKey().foreignKeyDefinition() ) );
			}
		}
	}
}
 
Example #7
Source File: PropertyBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the value generation strategy for the given property, if any.
 */
private ValueGeneration getValueGenerationFromAnnotations(XProperty property) {
	AnnotationValueGeneration<?> valueGeneration = null;

	for ( Annotation annotation : property.getAnnotations() ) {
		AnnotationValueGeneration<?> candidate = getValueGenerationFromAnnotation( property, annotation );

		if ( candidate != null ) {
			if ( valueGeneration != null ) {
				throw new AnnotationException(
						"Only one generator annotation is allowed:" + StringHelper.qualify(
								holder.getPath(),
								name
						)
				);
			}
			else {
				valueGeneration = candidate;
			}
		}
	}

	return valueGeneration;
}
 
Example #8
Source File: OptimizerFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the optimizer to use when there was not one explicitly specified.
 */
public static String determineImplicitOptimizerName(int incrementSize, Properties configSettings) {
	if ( incrementSize <= 1 ) {
		return StandardOptimizerDescriptor.NONE.getExternalName();
	}

	// see if the user defined a preferred pooled optimizer...
	final String preferredPooledOptimizerStrategy = configSettings.getProperty( AvailableSettings.PREFERRED_POOLED_OPTIMIZER );
	if ( StringHelper.isNotEmpty( preferredPooledOptimizerStrategy ) ) {
		return preferredPooledOptimizerStrategy;
	}

	// otherwise fallback to the fallback strategy (considering the deprecated PREFER_POOLED_VALUES_LO setting)
	return ConfigurationHelper.getBoolean( AvailableSettings.PREFER_POOLED_VALUES_LO, configSettings, false )
			? StandardOptimizerDescriptor.POOLED_LO.getExternalName()
			: StandardOptimizerDescriptor.POOLED.getExternalName();
}
 
Example #9
Source File: DefaultEntityAliases.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String[][] getSuffixedPropertyAliases(Loadable persister) {
	final int size = persister.getPropertyNames().length;
	final String[][] suffixedPropertyAliases;
	if (size > 0) {
		suffixedPropertyAliases = new String[size][];
		for ( int j = 0; j < size; j++ ) {
			suffixedPropertyAliases[j] = getUserProvidedAliases(
					persister.getPropertyNames()[j],
					getPropertyAliases( persister, j )
			);
			suffixedPropertyAliases[j] = StringHelper.unquote( suffixedPropertyAliases[j], persister.getFactory().getDialect() );
			intern( suffixedPropertyAliases[j] );
		}
	}
	else {
		suffixedPropertyAliases = EMPTY_ARRAY_OF_ARRAY_OF_STRINGS;
	}
	return suffixedPropertyAliases;
}
 
Example #10
Source File: MetadataBuilderImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ArrayList<MetadataSourceType> resolveInitialSourceProcessOrdering(ConfigurationService configService) {
	final ArrayList<MetadataSourceType> initialSelections = new ArrayList<>();

	final String sourceProcessOrderingSetting = configService.getSetting(
			AvailableSettings.ARTIFACT_PROCESSING_ORDER,
			StandardConverters.STRING
	);
	if ( sourceProcessOrderingSetting != null ) {
		final String[] orderChoices = StringHelper.split( ",; ", sourceProcessOrderingSetting, false );
		initialSelections.addAll( CollectionHelper.arrayList( orderChoices.length ) );
		for ( String orderChoice : orderChoices ) {
			initialSelections.add( MetadataSourceType.parsePrecedence( orderChoice ) );
		}
	}
	if ( initialSelections.isEmpty() ) {
		initialSelections.add( MetadataSourceType.HBM );
		initialSelections.add( MetadataSourceType.CLASS );
	}

	return initialSelections;
}
 
Example #11
Source File: IdentifierSourceNonAggregatedCompositeImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private EmbeddableSource interpretIdClass(
		MappingDocument mappingDocument,
		JaxbHbmCompositeIdType jaxbHbmCompositeIdMapping) {
	// if <composite-id/> is null here we have much bigger problems :)

	if ( !jaxbHbmCompositeIdMapping.isMapped() ) {
		return null;
	}

	final String className = jaxbHbmCompositeIdMapping.getClazz();
	if ( StringHelper.isEmpty( className ) ) {
		return null;
	}

	final String idClassQualifiedName = mappingDocument.qualifyClassName( className );
	final JavaTypeDescriptor idClassTypeDescriptor = new JavaTypeDescriptor() {
		@Override
		public String getName() {
			return idClassQualifiedName;
		}
	};
	return new IdClassSource( idClassTypeDescriptor, rootEntitySource, mappingDocument );
}
 
Example #12
Source File: PropertyAccessStrategyResolverStandardImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public PropertyAccessStrategy resolvePropertyAccessStrategy(
		Class containerClass,
		String explicitAccessStrategyName,
		EntityMode entityMode) {

	if ( BuiltInPropertyAccessStrategies.BASIC.getExternalName().equals( explicitAccessStrategyName )
			|| BuiltInPropertyAccessStrategies.FIELD.getExternalName().equals( explicitAccessStrategyName )
			|| BuiltInPropertyAccessStrategies.MIXED.getExternalName().equals( explicitAccessStrategyName ) ) {
		if ( Managed.class.isAssignableFrom( containerClass ) ) {
			// PROPERTY (BASIC) and MIXED are not valid for bytecode enhanced entities...
			return PropertyAccessStrategyEnhancedImpl.INSTANCE;
		}
	}

	if ( StringHelper.isNotEmpty( explicitAccessStrategyName ) ) {
		return resolveExplicitlyNamedPropertyAccessStrategy( explicitAccessStrategyName );
	}

	if ( entityMode == EntityMode.MAP ) {
		return BuiltInPropertyAccessStrategies.MAP.getStrategy();
	}
	else {
		return BuiltInPropertyAccessStrategies.BASIC.getStrategy();
	}
}
 
Example #13
Source File: AbstractPropertyMapping.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public String[] toColumns(String alias, String propertyName) throws QueryException {
	//TODO: *two* hashmap lookups here is one too many...
	String[] columns = columnsByPropertyPath.get( propertyName );
	if ( columns == null ) {
		throw propertyException( propertyName );
	}
	String[] formulaTemplates = formulaTemplatesByPropertyPath.get( propertyName );
	String[] columnReaderTemplates = columnReaderTemplatesByPropertyPath.get( propertyName );
	String[] result = new String[columns.length];
	for ( int i = 0; i < columns.length; i++ ) {
		if ( columnReaderTemplates[i] == null ) {
			result[i] = StringHelper.replace( formulaTemplates[i], Template.TEMPLATE, alias );
		}
		else {
			result[i] = StringHelper.replace( columnReaderTemplates[i], Template.TEMPLATE, alias );
		}
	}
	return result;
}
 
Example #14
Source File: SingleLineSqlCommandExtractor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String[] extractCommands(Reader reader) {
	BufferedReader bufferedReader = new BufferedReader( reader );
	List<String> statementList = new LinkedList<String>();
	try {
		for ( String sql = bufferedReader.readLine(); sql != null; sql = bufferedReader.readLine() ) {
			String trimmedSql = sql.trim();
			if ( StringHelper.isEmpty( trimmedSql ) || isComment( trimmedSql ) ) {
				continue;
			}
			if ( trimmedSql.endsWith( ";" ) ) {
				trimmedSql = trimmedSql.substring( 0, trimmedSql.length() - 1 );
			}
			statementList.add( trimmedSql );
		}
		return statementList.toArray( new String[statementList.size()] );
	}
	catch ( IOException e ) {
		throw new ImportScriptException( "Error during import script parsing.", e );
	}
}
 
Example #15
Source File: SchemaDropperImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applySqlString(
		String sqlString,
		Formatter formatter,
		ExecutionOptions options,
		GenerationTarget... targets) {
	if ( StringHelper.isEmpty( sqlString ) ) {
		return;
	}

	String sqlStringFormatted = formatter.format( sqlString );
	for ( GenerationTarget target : targets ) {
		try {
			target.accept( sqlStringFormatted );
		}
		catch (CommandAcceptanceException e) {
			options.getExceptionHandler().handleException( e );
		}
	}
}
 
Example #16
Source File: JPAOverriddenAnnotationReader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static ColumnResult buildColumnResult(
			Element columnResultElement,
			XMLContext.Default defaults,
			ClassLoaderAccess classLoaderAccess) {
//		AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
//		copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
//		return AnnotationFactory.create( columnResultDescriptor );

		AnnotationDescriptor columnResultDescriptor = new AnnotationDescriptor( ColumnResult.class );
		copyStringAttribute( columnResultDescriptor, columnResultElement, "name", true );
		final String columnTypeName = columnResultElement.attributeValue( "class" );
		if ( StringHelper.isNotEmpty( columnTypeName ) ) {
			columnResultDescriptor.setValue( "type", resolveClassReference( columnTypeName, defaults, classLoaderAccess ) );
		}
		return AnnotationFactory.create( columnResultDescriptor );
	}
 
Example #17
Source File: PathHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Turns a path into an AST.
 *
 * @param path    The path.
 * @param factory The AST factory to use.
 * @return An HQL AST representing the path.
 */
public static AST parsePath(String path, ASTFactory factory) {
	String[] identifiers = StringHelper.split( ".", path );
	AST lhs = null;
	for ( int i = 0; i < identifiers.length; i++ ) {
		String identifier = identifiers[i];
		AST child = ASTUtil.create( factory, HqlSqlTokenTypes.IDENT, identifier );
		if ( i == 0 ) {
			lhs = child;
		}
		else {
			lhs = ASTUtil.createBinarySubtree( factory, HqlSqlTokenTypes.DOT, ".", lhs, child );
		}
	}
	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "parsePath() : %s -> %s", path, ASTUtil.getDebugString( lhs ) );
	}
	return lhs;
}
 
Example #18
Source File: DefaultNamingStrategy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the property name or propertyTableName
 */
public String foreignKeyColumnName(
		String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName
) {
	String header = propertyName != null ? StringHelper.unqualify( propertyName ) : propertyTableName;
	if (header == null) throw new AssertionFailure("NammingStrategy not properly filled");
	return columnName( header ); //+ "_" + referencedColumnName not used for backward compatibility
}
 
Example #19
Source File: Identifier.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Means to generate an {@link Identifier} instance from its simple text form.
 * <p/>
 * If passed text is {@code null}, {@code null} is returned.
 * <p/>
 * If passed text is surrounded in quote markers, the generated Identifier
 * is considered quoted.  Quote markers include back-ticks (`), and
 * double-quotes (").
 *
 * @param text The text form
 *
 * @return The identifier form, or {@code null} if text was {@code null}
 */
public static Identifier toIdentifier(String text) {
	if ( StringHelper.isEmpty( text ) ) {
		return null;
	}
	final String trimmedText = text.trim();
	if ( isQuoted( trimmedText ) ) {
		final String bareName = trimmedText.substring( 1, trimmedText.length() - 1 );
		return new Identifier( bareName, true );
	}
	else {
		return new Identifier( trimmedText, false );
	}
}
 
Example #20
Source File: AbstractSchemaMigrator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void applyIndexes(
		Table table,
		TableInformation tableInformation,
		Dialect dialect,
		Metadata metadata,
		Formatter formatter,
		ExecutionOptions options,
		GenerationTarget... targets) {
	final Exporter<Index> exporter = dialect.getIndexExporter();

	final Iterator<Index> indexItr = table.getIndexIterator();
	while ( indexItr.hasNext() ) {
		final Index index = indexItr.next();
		if ( !StringHelper.isEmpty( index.getName() ) ) {
			IndexInformation existingIndex = null;
			if ( tableInformation != null ) {
				existingIndex = findMatchingIndex( index, tableInformation );
			}
			if ( existingIndex == null ) {
				applySqlStrings(
						false,
						exporter.getSqlCreateStrings( index, metadata ),
						formatter,
						options,
						targets
				);
			}
		}
	}
}
 
Example #21
Source File: JavaConstantNode.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setText(String s) {
	// for some reason the antlr.CommonAST initialization routines force
	// this method to get called twice.  The first time with an empty string
	if ( StringHelper.isNotEmpty( s ) ) {
		constantExpression = s;
		constantValue = ReflectHelper.getConstantValue( s, factory );
		heuristicType = factory.getTypeResolver().heuristicType( constantValue.getClass().getName() );
		super.setText( s );
	}
}
 
Example #22
Source File: ReactiveDynamicBatchingEntityLoader.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
static String expandBatchIdPlaceholder(
		String sql,
		Serializable[] ids,
		String alias,
		String[] keyColumnNames,
		Dialect dialect) {
	if ( keyColumnNames.length == 1 ) {
		// non-composite
		return StringHelper.replace( sql, StringHelper.BATCH_ID_PLACEHOLDER, StringHelper.repeat( "?", ids.length, "," ) );
	}
	else {
		// composite
		if ( dialect.supportsRowValueConstructorSyntaxInInList() ) {
			final String tuple = '(' + StringHelper.repeat( "?", keyColumnNames.length, "," ) + ')';
			return StringHelper.replace( sql, StringHelper.BATCH_ID_PLACEHOLDER, StringHelper.repeat( tuple, ids.length, "," ) );
		}
		else {
			final String keyCheck = '(' + StringHelper.joinWithQualifierAndSuffix(
					keyColumnNames,
					alias,
					" = ?",
					" and "
			) + ')';
			return StringHelper.replace( sql, StringHelper.BATCH_ID_PLACEHOLDER, StringHelper.repeat( keyCheck, ids.length, " or " ) );
		}
	}
}
 
Example #23
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Identifier determineCatalogName(TableSpecificationSource tableSpecSource) {
	if ( StringHelper.isNotEmpty( tableSpecSource.getExplicitCatalogName() ) ) {
		return database.toIdentifier( tableSpecSource.getExplicitCatalogName() );
	}
	else {
		return database.getDefaultNamespace().getName().getCatalog();
	}
}
 
Example #24
Source File: AbstractPropertyHolder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static Map<String, JoinColumn[]> buildJoinColumnOverride(XAnnotatedElement element, String path) {
	Map<String, JoinColumn[]> columnOverride = new HashMap<String, JoinColumn[]>();
	if ( element != null ) {
		AssociationOverride[] overrides = buildAssociationOverrides( element, path );
		if ( overrides != null ) {
			for ( AssociationOverride depAttr : overrides ) {
				columnOverride.put(
						StringHelper.qualify( path, depAttr.name() ),
						depAttr.joinColumns()
				);
			}
		}
	}
	return columnOverride;
}
 
Example #25
Source File: JoinHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static String[] toColumns(OuterJoinLoadable persister, String columnQualifier, int propertyIndex) {
	if ( propertyIndex >= 0 ) {
		return persister.toColumns( columnQualifier, propertyIndex );
	}
	else {
		final String[] cols = persister.getIdentifierColumnNames();
		final String[] result = new String[cols.length];

		for ( int j = 0; j < cols.length; j++ ) {
			result[j] = StringHelper.qualify( columnQualifier, cols[j] );
		}

		return result;
	}
}
 
Example #26
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void bindEjb3Annotation(Entity ejb3Ann) {
	if ( ejb3Ann == null ) throw new AssertionFailure( "@Entity should always be not null" );
	if ( BinderHelper.isEmptyAnnotationValue( ejb3Ann.name() ) ) {
		name = StringHelper.unqualify( annotatedClass.getName() );
	}
	else {
		name = ejb3Ann.name();
	}
}
 
Example #27
Source File: AbstractEntitySourceImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String[] getSynchronizedTableNames() {
	if ( CollectionHelper.isEmpty( jaxbEntityMapping.getSynchronize() ) ) {
		return StringHelper.EMPTY_STRINGS;
	}
	else {
		final int size = jaxbEntityMapping.getSynchronize().size();
		final String[] synchronizedTableNames = new String[size];
		for ( int i = 0; i < size; i++ ) {
			synchronizedTableNames[i] = jaxbEntityMapping.getSynchronize().get( i ).getTable();
		}
		return synchronizedTableNames;
	}
}
 
Example #28
Source File: RelationalValueSourceHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a {@link ColumnsAndFormulasSource}, build the corresponding list of
 * {@link ColumnSource}.  Any formula, rather than a column, will result in an exception.
 *
 * @param mappingDocument the mapping document
 * @param containingTableName The logical name of the table containing the relational values
 * @param columnsAndFormulasSource the adapter describing the value sources.
 *
 * @return The corresponding list.
 */
public static List<ColumnSource> buildColumnSources(
		MappingDocument mappingDocument,
		String containingTableName,
		RelationalValueSourceHelper.ColumnsAndFormulasSource columnsAndFormulasSource) {
	final List<RelationalValueSource> sources = buildValueSources(
			mappingDocument,
			containingTableName,
			columnsAndFormulasSource
	);

	final List<ColumnSource> columnSources = CollectionHelper.arrayList( sources.size() );
	for ( RelationalValueSource source : sources ) {
		if ( !ColumnSource.class.isInstance( source ) ) {
			final String errorMessage;
			if ( columnsAndFormulasSource.getSourceType().canBeNamed()
					&& StringHelper.isNotEmpty( columnsAndFormulasSource.getSourceName() ) ) {
				errorMessage = String.format(
						Locale.ENGLISH,
						"Expecting only columns in context of <%s name=\"%s\"/>, but found formula [%s]",
						columnsAndFormulasSource.getSourceType().getElementName(),
						columnsAndFormulasSource.getSourceName(),
						( (DerivedValueSource) source ).getExpression()
				);
			}
			else {
				errorMessage = String.format(
						Locale.ENGLISH,
						"Expecting only columns in context of <%s/>, but found formula [%s]",
						columnsAndFormulasSource.getSourceType().getElementName(),
						( (DerivedValueSource) source ).getExpression()
				);
			}
			throw new MappingException( errorMessage, mappingDocument.getOrigin() );
		}
		columnSources.add( (ColumnSource) source );
	}
	return columnSources;
}
 
Example #29
Source File: EntityNamingSourceImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public EntityNamingSourceImpl(String entityName, String className, String jpaEntityName) {
	this.entityName = entityName;
	this.className = className;
	this.jpaEntityName = jpaEntityName;

	this.typeName = StringHelper.isNotEmpty( className ) ? className : entityName;
}
 
Example #30
Source File: NotNullExpression.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	final String[] columns = criteriaQuery.findColumns( propertyName, criteria );
	String result = String.join(
			" or ",
			StringHelper.suffix( columns, " is not null" )
	);
	if ( columns.length > 1 ) {
		result = '(' + result + ')';
	}
	return result;
}