Java Code Examples for org.hibernate.dialect.Dialect

The following examples show how to use org.hibernate.dialect.Dialect. 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
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 2
@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 3
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 4
/**
 * 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 Project: lams   Source File: LikeExpression.java    License: 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 6
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 7
Source Project: lams   Source File: JdbcEnvironmentImpl.java    License: 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 Project: lams   Source File: Index.java    License: 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 9
Source Project: lams   Source File: TableGenerator.java    License: 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 Project: cacheonix-core   Source File: Loader.java    License: 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 11
protected String buildUpdateQuery(Dialect dialect) {
	String update = "update " + renderedTableName
			+ " set " + valueColumnName + "=?"
			+ " where " + valueColumnName + "=?";
	if (segmentColumnName != null) {
		update += " and " + segmentColumnName + "=?";
	}
	return update;
}
 
Example 12
@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 13
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 14
Source Project: lams   Source File: PrimaryKey.java    License: 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 15
Source Project: lams   Source File: StringHelper.java    License: 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 16
Source Project: lams   Source File: DateType.java    License: 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 );
}
 
Example 17
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 18
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 19
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 20
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 21
Source Project: unitime   Source File: HibernateUtil.java    License: 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 22
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 23
Source Project: lams   Source File: AbstractSchemaMigrator.java    License: 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 24
Source Project: cacheonix-core   Source File: Index.java    License: 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 25
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 26
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
		PostInsertIdentityPersister persister,
		Dialect dialect,
		boolean isGetGeneratedKeysEnabled) throws HibernateException {
	return new Delegate( persister, dialect, getSequenceName() );
}
 
Example 27
Source Project: lams   Source File: Constraint.java    License: 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 28
Source Project: lams   Source File: UniqueKey.java    License: 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 29
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 30
public void validateSchema(Dialect dialect, DatabaseMetadata databaseMetadata)
		throws HibernateException {
	secondPassCompile();

	String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG );
	String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA );
	
	Iterator iter = getTableMappings();
	while ( iter.hasNext() ) {
		Table table = (Table) iter.next();
		if ( table.isPhysicalTable() ) {
			

			TableMetadata tableInfo = databaseMetadata.getTableMetadata(
					table.getName(),
					( table.getSchema() == null ) ? defaultSchema : table.getSchema(),
					( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(),
							table.isQuoted());
			if ( tableInfo == null ) {
				throw new HibernateException( "Missing table: " + table.getName() );
			}
			else {
				table.validateColumns( dialect, mapping, tableInfo );
			}

		}
	}

	iter = iterateGenerators( dialect );
	while ( iter.hasNext() ) {
		PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next();
		Object key = generator.generatorKey();
		if ( !databaseMetadata.isSequence( key ) && !databaseMetadata.isTable( key ) ) {
			throw new HibernateException( "Missing sequence or table: " + key );
		}
	}
}