下面列出了怎么用org.hibernate.internal.util.StringHelper的API类实例代码及写法,或者点击链接到github查看源代码。
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 );
}
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() ) );
}
}
}
}
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();
}
}
/**
* 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;
}
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 );
}
}
}
@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();
}
}
@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()
);
}
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;
}
@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 );
}
}
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 );
}
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;
}
@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;
}
/**
* 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();
}
/**
* 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;
}
/**
* 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>"An argument to the multiselect method must not be a tuple-
* or array-valued compound selection item."</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() );
}
}
}
}
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
);
}
}
}
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 );
}
}
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 " ) );
}
}
}
public final CompletionStage<Void> doBatchedCollectionLoad(
final SessionImplementor session,
final Serializable[] ids,
final Type type) throws HibernateException {
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Batch loading collection: %s",
collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
);
}
final Type[] idTypes = new Type[ids.length];
Arrays.fill( idTypes, type );
final QueryParameters queryParameters = new QueryParameters( idTypes, ids, ids );
final String sql = StringHelper.expandBatchIdPlaceholder(
sqlTemplate,
ids,
alias,
collectionPersister().getKeyColumnNames(),
session.getJdbcServices().getJdbcEnvironment().getDialect()
);
return doReactiveQueryAndInitializeNonLazyCollections( sql, session, queryParameters )
.handle( (list, err) -> {
CompletionStages.logSqlException( err,
() -> "could not initialize a collection batch: " +
collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
getSQLString()
);
LOG.debug("Done batch load");
return CompletionStages.returnNullorRethrow( err );
} );
}
@Override
public String getAddForeignKeyConstraintString(
String constraintName,
String[] foreignKey,
String referencedTable,
String[] primaryKey,
boolean referencesPrimaryKey) {
final String cols = StringHelper.join( ", ", foreignKey );
// 设置foreignkey对应的列值可以为空
return " ALTER "+ cols +" SET DEFAULT NULL " ;
}
public SelectFragment addColumn(String tableAlias, String columnName, String columnAlias) {
columns.add( StringHelper.qualify(tableAlias, columnName) );
//columns.add(columnName);
//aliases.add(tableAlias);
columnAliases.add(columnAlias);
return this;
}
@Override
public void traceIn(String ruleName) {
if ( inputState.guessing > 0 ) {
return;
}
String prefix = StringHelper.repeat( '-', ( traceDepth++ * 2 ) ) + "-> ";
LOG.trace( prefix + ruleName );
}
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
final String[] lhsColumns = criteriaQuery.findColumns( propertyName, criteria );
final String[] rhsColumns = criteriaQuery.findColumns( otherPropertyName, criteria );
final String[] comparisons = StringHelper.add( lhsColumns, getOp(), rhsColumns );
if ( comparisons.length > 1 ) {
return '(' + String.join( " and ", comparisons ) + ')';
}
else {
return comparisons[0];
}
}
private static String interpretSorting(String sort) {
if ( StringHelper.isEmpty( sort ) ) {
return null;
}
if ( "unsorted".equals( sort ) ) {
return null;
}
return sort;
}
public PluralAttributeKeySourceImpl(
MappingDocument mappingDocument,
final JaxbHbmManyToOneType jaxbKey,
final AttributeSourceContainer container) {
super( mappingDocument );
this.explicitFkName = StringHelper.nullIfEmpty( jaxbKey.getForeignKey() );
this.referencedPropertyName = StringHelper.nullIfEmpty( jaxbKey.getPropertyRef() );
this.cascadeDeletesAtFkLevel = jaxbKey.getOnDelete() != null
&& "cascade".equals( jaxbKey.getOnDelete().value() );
this.nullable = jaxbKey.isNotNull() == null || !jaxbKey.isNotNull();
this.updateable = jaxbKey.isUpdate();
this.valueSources = RelationalValueSourceHelper.buildValueSources(
sourceMappingDocument(),
null, // todo : collection table name
new RelationalValueSourceHelper.AbstractColumnsAndFormulasSource() {
@Override
public XmlElementMetadata getSourceType() {
return XmlElementMetadata.KEY;
}
@Override
public String getSourceName() {
return null;
}
@Override
public String getColumnAttribute() {
return StringHelper.nullIfEmpty( jaxbKey.getColumnAttribute() );
}
@Override
public List getColumnOrFormulaElements() {
return jaxbKey.getColumnOrFormula();
}
}
);
}
public String[] toColumns(String alias, String propertyName) throws QueryException {
if (propertyName==null || "id".equals(propertyName) ) {
return StringHelper.qualify( alias, elementColumns );
}
else {
throw new QueryException("cannot dereference scalar collection element: " + propertyName);
}
}
@Override
protected AttributeConversionInfo locateAttributeConversionInfo(String path) {
final String embeddedPath = StringHelper.qualifyConditionally( embeddedAttributeName, path );
AttributeConversionInfo fromParent = parent.locateAttributeConversionInfo( embeddedPath );
if ( fromParent != null ) {
return fromParent;
}
AttributeConversionInfo fromEmbedded = attributeConversionInfoMap.get( embeddedPath );
if ( fromEmbedded != null ) {
return fromEmbedded;
}
return attributeConversionInfoMap.get( path );
}
protected void appendComponentCondition(
String path,
Object component,
CompositeType type,
Criteria criteria,
CriteriaQuery criteriaQuery,
StringBuilder buf) {
if ( component != null ) {
final String[] propertyNames = type.getPropertyNames();
final Object[] values = type.getPropertyValues( component, getEntityMode( criteria, criteriaQuery ) );
final Type[] subtypes = type.getSubtypes();
for ( int i=0; i<propertyNames.length; i++ ) {
final String subPath = StringHelper.qualify( path, propertyNames[i] );
final Object value = values[i];
if ( isPropertyIncluded( value, subPath, subtypes[i] ) ) {
final Type subtype = subtypes[i];
if ( subtype.isComponentType() ) {
appendComponentCondition(
subPath,
value,
(CompositeType) subtype,
criteria,
criteriaQuery,
buf
);
}
else {
appendPropertyCondition(
subPath,
value,
criteria,
criteriaQuery,
buf
);
}
}
}
}
}
/**
* 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
}
/**
* 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 );
}
}