org.hibernate.dialect.Dialect Java Examples

The following examples show how to use org.hibernate.dialect.Dialect. 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: MultipleHiLoPerTableGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException {
	return new String[] {
		new StringBuffer( dialect.getCreateTableString() )
				.append( ' ' )
				.append( tableName )
				.append( " ( " )
				.append( pkColumnName )
				.append( ' ' )
				.append( dialect.getTypeName( Types.VARCHAR, keySize, 0, 0 ) )
				.append( ",  " )
				.append( valueColumnName )
				.append( ' ' )
				.append( dialect.getTypeName( Types.INTEGER ) )
				.append( " ) " )
				.toString()
	};
}
 
Example #2
Source File: LikeExpression.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String toSqlString(Criteria criteria,CriteriaQuery criteriaQuery) {
	final Dialect dialect = criteriaQuery.getFactory().getDialect();
	final String[] columns = criteriaQuery.findColumns( propertyName, criteria );
	if ( columns.length != 1 ) {
		throw new HibernateException( "Like may only be used with single-column properties" );
	}

	final String escape = escapeChar == null ? "" : " escape \'" + escapeChar + "\'";
	final String column = columns[0];
	if ( ignoreCase ) {
		if ( dialect.supportsCaseInsensitiveLike() ) {
			return column +" " + dialect.getCaseInsensitiveLike() + " ?" + escape;
		}
		else {
			return dialect.getLowercaseFunction() + '(' + column + ')' + " like ?" + escape;
		}
	}
	else {
		return column + " like ?" + escape;
	}
}
 
Example #3
Source File: DefaultIdentifierGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
	public void setDialect(Dialect dialect) {
//		LOG.debugf( "Setting dialect [%s]", dialect );
//		this.dialect = dialect;
//
//		if ( dialect == jdbcEnvironment.getDialect() ) {
//			LOG.debugf(
//					"Call to unsupported method IdentifierGeneratorFactory#setDialect; " +
//							"ignoring as passed Dialect matches internal Dialect"
//			);
//		}
//		else {
//			throw new UnsupportedOperationException(
//					"Call to unsupported method IdentifierGeneratorFactory#setDialect attempting to" +
//							"set a non-matching Dialect : " + dialect.getClass().getName()
//			);
//		}
	}
 
Example #4
Source File: SQLExceptionConverterFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Build a SQLExceptionConverter instance.
 * <p/>
 * First, looks for a {@link Environment.SQL_EXCEPTION_CONVERTER} property to see
 * if the configuration specified the class of a specific converter to use.  If this
 * property is set, attempt to construct an instance of that class.  If not set, or
 * if construction fails, the converter specific to the dialect will be used.
 *
 * @param dialect    The defined dialect.
 * @param properties The configuration properties.
 * @return An appropriate SQLExceptionConverter instance.
 * @throws HibernateException There was an error building the SQLExceptionConverter.
 */
public static SQLExceptionConverter buildSQLExceptionConverter(Dialect dialect, Properties properties) throws HibernateException {
	SQLExceptionConverter converter = null;

	String converterClassName = ( String ) properties.get( Environment.SQL_EXCEPTION_CONVERTER );
	if ( StringHelper.isNotEmpty( converterClassName ) ) {
		converter = constructConverter( converterClassName, dialect.getViolatedConstraintNameExtracter() );
	}

	if ( converter == null ) {
		log.trace( "Using dialect defined converter" );
		converter = dialect.buildSQLExceptionConverter();
	}

	if ( converter instanceof Configurable ) {
		try {
			( ( Configurable ) converter ).configure( properties );
		}
		catch ( HibernateException e ) {
			log.warn( "Unable to configure SQLExceptionConverter", e );
			throw e;
		}
	}

	return converter;
}
 
Example #5
Source File: Index.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static String buildSqlCreateIndexString(
		Dialect dialect,
		String name,
		Table table,
		Iterator<Column> columns,
		boolean unique,
		String defaultCatalog,
		String defaultSchema) {
	return buildSqlCreateIndexString(
			dialect,
			name,
			table,
			columns,
			Collections.EMPTY_MAP,
			unique,
			defaultCatalog,
			defaultSchema
	);
}
 
Example #6
Source File: MySQLEncryptTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
private void setEncryptionKey(EntityManager entityManager) {
	Session session = entityManager.unwrap(Session.class);
	Dialect dialect = session.getSessionFactory().unwrap(SessionFactoryImplementor.class).getJdbcServices().getDialect();
	String encryptionKey = ReflectionUtils.invokeMethod(
		dialect,
		"escapeLiteral",
		"encryptionKey"
	);

	session.doWork(connection -> {
		update(
			connection,
			String.format(
				"SET @encryption_key = '%s'", encryptionKey
			)
		);
	});
}
 
Example #7
Source File: JdbcEnvironmentImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String determineCurrentSchemaName(
		DatabaseMetaData databaseMetaData,
		ServiceRegistry serviceRegistry,
		Dialect dialect) throws SQLException {
	final SchemaNameResolver schemaNameResolver;

	final Object setting = serviceRegistry.getService( ConfigurationService.class ).getSettings().get( SCHEMA_NAME_RESOLVER );
	if ( setting == null ) {
		schemaNameResolver = dialect.getSchemaNameResolver();
	}
	else {
		schemaNameResolver = serviceRegistry.getService( StrategySelector.class ).resolveDefaultableStrategy(
				SchemaNameResolver.class,
				setting,
				dialect.getSchemaNameResolver()
		);
	}

	try {
		return schemaNameResolver.resolveSchemaName( databaseMetaData.getConnection(), dialect );
	}
	catch (Exception e) {
		log.debug( "Unable to resolve connection default schema", e );
		return null;
	}
}
 
Example #8
Source File: StandardAnsiSqlAggregationFunctions.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String renderCountDistinct(List arguments, Dialect dialect) {
	final StringBuilder buffer = new StringBuilder();
	buffer.append( "count(distinct " );
	if (dialect.requiresParensForTupleDistinctCounts()) {
		buffer.append("(");
	}
	String sep = "";
	final Iterator itr = arguments.iterator();
	// intentionally skip first
	itr.next();
	while ( itr.hasNext() ) {
		buffer.append( sep ).append( itr.next() );
		sep = ", ";
	}
	if (dialect.requiresParensForTupleDistinctCounts()) {
		buffer.append(")");
	}
	return buffer.append( ")" ).toString();
}
 
Example #9
Source File: TableGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException {
	return new String[] {
			dialect.getCreateTableString() + ' ' + renderedTableName + " ( "
					+ segmentColumnName + ' ' + dialect.getTypeName( Types.VARCHAR, segmentValueLength, 0, 0 ) + " not null "
					+ ", " + valueColumnName + ' ' + dialect.getTypeName( Types.BIGINT )
					+ ", primary key ( " + segmentColumnName + " ) )" + dialect.getTableTypeString()
	};
}
 
Example #10
Source File: Index.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static String buildSqlCreateIndexString(
		Dialect dialect,
		String name,
		Table table,
		Iterator columns,
		boolean unique,
		String defaultCatalog,
		String defaultSchema
) {
	//TODO handle supportsNotNullUnique=false, but such a case does not exist in the wild so far
	StringBuffer buf = new StringBuffer( "create" )
			.append( unique ?
					" unique" :
					"" )
			.append( " index " )
			.append( dialect.qualifyIndexName() ?
					name :
					StringHelper.unqualify( name ) )
			.append( " on " )
			.append( table.getQualifiedName( dialect, defaultCatalog, defaultSchema ) )
			.append( " (" );
	Iterator iter = columns;
	while ( iter.hasNext() ) {
		buf.append( ( (Column) iter.next() ).getQuotedName( dialect ) );
		if ( iter.hasNext() ) buf.append( ", " );
	}
	buf.append( ")" );
	return buf.toString();
}
 
Example #11
Source File: IdentityGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
		PostInsertIdentityPersister persister,
		Dialect dialect,
		boolean isGetGeneratedKeysEnabled) throws HibernateException {
	if ( isGetGeneratedKeysEnabled ) {
		return dialect.getIdentityColumnSupport().buildGetGeneratedKeysDelegate( persister, dialect );
	}
	else if ( dialect.getIdentityColumnSupport().supportsInsertSelectIdentity() ) {
		return new InsertSelectDelegate( persister, dialect );
	}
	else {
		return new BasicDelegate( persister, dialect );
	}
}
 
Example #12
Source File: Loader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Some dialect-specific LIMIT clauses require the maximium last row number
 * (aka, first_row_number + total_row_count), while others require the maximum
 * returned row count (the total maximum number of rows to return).
 *
 * @param selection The selection criteria
 * @param dialect The dialect
 * @return The appropriate value to bind into the limit clause.
 */
private static int getMaxOrLimit(final RowSelection selection, final Dialect dialect) {
	final int firstRow = getFirstRow( selection );
	final int lastRow = selection.getMaxRows().intValue();
	if ( dialect.useMaxForLimit() ) {
		return lastRow + firstRow;
	}
	else {
		return lastRow;
	}
}
 
Example #13
Source File: HibernateUtil.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static void addAddDateToDialect() {
	SessionFactoryImplementor hibSessionFactory = (SessionFactoryImplementor)new _RootDAO().getSession().getSessionFactory();
	Dialect dialect = hibSessionFactory.getDialect();
	if (isPostgress() && !dialect.getFunctions().containsKey("adddate")) {
		dialect.getFunctions().put("adddate", new SQLFunctionTemplate(IntegerType.INSTANCE, "?1 + (?2) * interval '1 day'"));
	}
}
 
Example #14
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void processExportableProducers() {
	// for now we only handle id generators as ExportableProducers

	final Dialect dialect = getDatabase().getJdbcEnvironment().getDialect();
	final String defaultCatalog = extractName( getDatabase().getDefaultNamespace().getName().getCatalog(), dialect );
	final String defaultSchema = extractName( getDatabase().getDefaultNamespace().getName().getSchema(), dialect );

	for ( PersistentClass entityBinding : entityBindingMap.values() ) {
		if ( entityBinding.isInherited() ) {
			continue;
		}

		handleIdentifierValueBinding(
				entityBinding.getIdentifier(),
				dialect,
				defaultCatalog,
				defaultSchema,
				(RootClass) entityBinding
		);
	}

	for ( Collection collection : collectionBindingMap.values() ) {
		if ( !IdentifierCollection.class.isInstance( collection ) ) {
			continue;
		}

		handleIdentifierValueBinding(
				( (IdentifierCollection) collection ).getIdentifier(),
				dialect,
				defaultCatalog,
				defaultSchema,
				null
		);
	}
}
 
Example #15
Source File: UniqueIdGenerator.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void configure(Type type, Properties params, Dialect d) throws MappingException {
    if (getGenerator() instanceof Configurable) {
        if (params.getProperty("schema") == null && sDefaultSchema != null)
            params.setProperty("schema", sDefaultSchema);
        if (params.get("identifier_normalizer") == null && sNormalizer != null)
        	params.put("identifier_normalizer", sNormalizer);
        ((Configurable)getGenerator()).configure(type, params, d);
    }
}
 
Example #16
Source File: AbstractCteValuesListBulkIdHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AbstractCteValuesListBulkIdHandler(
		SessionFactoryImplementor sessionFactory, HqlSqlWalker walker,
		String catalog, String schema) {
	super( sessionFactory, walker );
	Dialect dialect = sessionFactory.getServiceRegistry().getService( JdbcServices.class ).getDialect();
	if ( !dialect.supportsNonQueryWithCTE() ) {
		throw new UnsupportedOperationException(
				"The " + getClass().getSimpleName() +
						" can only be used with Dialects that support CTE that can take UPDATE or DELETE statements as well!"
		);
	}
	if ( !dialect.supportsValuesList() ) {
		throw new UnsupportedOperationException(
				"The " + getClass().getSimpleName() +
						" can only be used with Dialects that support VALUES lists!"
		);
	}
	if ( !dialect.supportsRowValueConstructorSyntaxInInList() ) {
		throw new UnsupportedOperationException(
				"The " + getClass().getSimpleName() +
						" can only be used with Dialects that support IN clause row-value expressions (for composite identifiers)!"
		);
	}

	this.jdbcEnvironment = sessionFactory.getServiceRegistry().getService(
			JdbcServices.class ).getJdbcEnvironment();
	this.catalog = catalog;
	this.schema = schema;
}
 
Example #17
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
	if ( !sqlTypeDescriptor.canBeRemapped() ) {
		return sqlTypeDescriptor;
	}

	final Dialect dialect = getJdbcServices().getJdbcEnvironment().getDialect();
	final SqlTypeDescriptor remapped = dialect.remapSqlTypeDescriptor( sqlTypeDescriptor );
	return remapped == null ? sqlTypeDescriptor : remapped;
}
 
Example #18
Source File: IdOrVersionGenerator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private String buildSelectVersionQuery(SessionImplementor session, String versionName, String idName, String tableName) {
	Dialect dialect = session.getFactory().getDialect();
	final String alias = "tbl";
	List<String> maxArgs = new ArrayList<>();
	maxArgs.add(StringHelper.qualify(alias, versionName));
	String maxFunction = dialect.getFunctions().get("max").render(IntegerType.INSTANCE, maxArgs, session.getFactory());
	String sql = "select " + maxFunction + " from " + tableName + ' ' + alias + " where " + StringHelper.qualify(alias, idName) + " = ?";
	return sql;
}
 
Example #19
Source File: AbstractTableBasedBulkIdHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected Select generateIdSelect(
		String tableAlias,
		ProcessedWhereClause whereClause) {

	final Dialect dialect = sessionFactory.getJdbcServices().getJdbcEnvironment().getDialect();

	final Select select = new Select( dialect );
	final SelectValues selectClause = new SelectValues( dialect ).addColumns(
			tableAlias,
			getTargetedQueryable().getIdentifierColumnNames(),
			getTargetedQueryable().getIdentifierColumnNames()
	);
	addAnyExtraIdSelectValues( selectClause );
	select.setSelectClause( selectClause.render() );

	String rootTableName = getTargetedQueryable().getTableName();
	String fromJoinFragment = getTargetedQueryable().fromJoinFragment( tableAlias, true, false );
	String whereJoinFragment = getTargetedQueryable().whereJoinFragment( tableAlias, true, false );

	select.setFromClause( rootTableName + ' ' + tableAlias + fromJoinFragment );

	if ( whereJoinFragment == null ) {
		whereJoinFragment = "";
	}
	else {
		whereJoinFragment = whereJoinFragment.trim();
		if ( whereJoinFragment.startsWith( "and" ) ) {
			whereJoinFragment = whereJoinFragment.substring( 4 );
		}
	}

	if ( whereClause.getUserWhereClauseFragment().length() > 0 ) {
		if ( whereJoinFragment.length() > 0 ) {
			whereJoinFragment += " and ";
		}
	}
	select.setWhereClause( whereJoinFragment + whereClause.getUserWhereClauseFragment() );
	return select;
}
 
Example #20
Source File: Assigned.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void configure(Type type, Properties params, Dialect d)
throws MappingException {
	entityName = params.getProperty(ENTITY_NAME);
	if (entityName==null) {
		throw new MappingException("no entity name");
	}
}
 
Example #21
Source File: AbstractSchemaMigrator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected abstract NameSpaceTablesInformation performTablesMigration(
Metadata metadata,
DatabaseInformation existingDatabase,
ExecutionOptions options,
Dialect dialect,
Formatter formatter,
Set<String> exportIdentifiers,
boolean tryToCreateCatalogs,
boolean tryToCreateSchemas,
Set<Identifier> exportedCatalogs,
Namespace namespace, GenerationTarget[] targets);
 
Example #22
Source File: DbTimestampType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Timestamp getCurrentTimestamp(SessionImplementor session) {
	Dialect dialect = session.getFactory().getDialect();
	String timestampSelectString = dialect.getCurrentTimestampSelectString();
	if ( dialect.isCurrentTimestampSelectStringCallable() ) {
		return useCallableStatement( timestampSelectString, session );
	}
	else {
		return usePreparedStatement( timestampSelectString, session );
	}
}
 
Example #23
Source File: SequenceIdentityGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
		PostInsertIdentityPersister persister,
		Dialect dialect,
		boolean isGetGeneratedKeysEnabled) throws HibernateException {
	return new Delegate( persister, dialect, getSequenceName() );
}
 
Example #24
Source File: UniqueKey.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public String sqlConstraintString(
			Dialect dialect,
			String constraintName,
			String defaultCatalog,
			String defaultSchema) {
//		return dialect.getUniqueDelegate().uniqueConstraintSql( this );
		// Not used.
		return "";
	}
 
Example #25
Source File: SelectGenerator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private SelectGeneratorDelegate(
		PostInsertIdentityPersister persister,
        Dialect dialect,
        String suppliedUniqueKeyPropertyName) {
	super( persister );
	this.persister = persister;
	this.dialect = dialect;
	this.uniqueKeyPropertyName = determineNameOfPropertyToUse( persister, suppliedUniqueKeyPropertyName );

	idSelectString = persister.getSelectByUniqueKeyString( uniqueKeyPropertyName );
	uniqueKeyType = persister.getPropertyType( uniqueKeyPropertyName );
	idType = persister.getIdentifierType();
}
 
Example #26
Source File: Constraint.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String sqlCreateString(Dialect dialect, Mapping p, String defaultCatalog, String defaultSchema) {
	if ( isGenerated( dialect ) ) {
		// Certain dialects (ex: HANA) don't support FKs as expected, but other constraints can still be created.
		// If that's the case, hasAlterTable() will be true, but getAddForeignKeyConstraintString will return
		// empty string.  Prevent blank "alter table" statements.
		String constraintString = sqlConstraintString( dialect, getName(), defaultCatalog, defaultSchema );
		if ( !StringHelper.isEmpty( constraintString ) ) {
			final String tableName = getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema );
			return dialect.getAlterTableString( tableName ) + " " + constraintString;
		}
	}
	return null;
}
 
Example #27
Source File: PrimaryKey.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String sqlConstraintString(Dialect dialect) {
	StringBuilder buf = new StringBuilder("primary key (");
	Iterator iter = getColumnIterator();
	while ( iter.hasNext() ) {
		buf.append( ( (Column) iter.next() ).getQuotedName(dialect) );
		if ( iter.hasNext() ) {
			buf.append(", ");
		}
	}
	return buf.append(')').toString();
}
 
Example #28
Source File: IdentifierGeneratorFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
	Class clazz = (Class) GENERATORS.get(strategy);
	if ( "native".equals(strategy) ) clazz = dialect.getNativeIdentifierGeneratorClass();
	try {
		if (clazz==null) clazz = ReflectHelper.classForName(strategy);
	}
	catch (ClassNotFoundException e) {
		throw new MappingException("could not interpret id generator strategy: " + strategy);
	}
	return clazz;
}
 
Example #29
Source File: StringHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static StringBuilder buildBatchFetchRestrictionFragment(
		String alias,
		String[] columnNames,
		Dialect dialect) {
	// the general idea here is to just insert a placeholder that we can easily find later...
	if ( columnNames.length == 1 ) {
		// non-composite key
		return new StringBuilder( StringHelper.qualify( alias, columnNames[0] ) )
				.append( " in (" ).append( BATCH_ID_PLACEHOLDER ).append( ")" );
	}
	else {
		// composite key - the form to use here depends on what the dialect supports.
		if ( dialect.supportsRowValueConstructorSyntaxInInList() ) {
			// use : (col1, col2) in ( (?,?), (?,?), ... )
			StringBuilder builder = new StringBuilder();
			builder.append( "(" );
			boolean firstPass = true;
			String deliminator = "";
			for ( String columnName : columnNames ) {
				builder.append( deliminator ).append( StringHelper.qualify( alias, columnName ) );
				if ( firstPass ) {
					firstPass = false;
					deliminator = ",";
				}
			}
			builder.append( ") in (" );
			builder.append( BATCH_ID_PLACEHOLDER );
			builder.append( ")" );
			return builder;
		}
		else {
			// use : ( (col1 = ? and col2 = ?) or (col1 = ? and col2 = ?) or ... )
			//		unfortunately most of this building needs to be held off until we know
			//		the exact number of ids :(
			return new StringBuilder( "(" ).append( BATCH_ID_PLACEHOLDER ).append( ")" );
		}
	}
}
 
Example #30
Source File: DateType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String objectToSQLString(Date value, Dialect dialect) throws Exception {
	final java.sql.Date jdbcDate = java.sql.Date.class.isInstance( value )
			? ( java.sql.Date ) value
			: new java.sql.Date( value.getTime() );
	// TODO : use JDBC date literal escape syntax? -> {d 'date-string'} in yyyy-mm-dd format
	return StringType.INSTANCE.objectToSQLString( jdbcDate.toString(), dialect );
}