org.hibernate.mapping.Table Java Examples

The following examples show how to use org.hibernate.mapping.Table. 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: LocalTemporaryTableBulkIdStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected IdTableInfoImpl buildIdTableInfo(
		PersistentClass entityBinding,
		Table idTable,
		JdbcServices jdbcServices,
		MetadataImplementor metadata,
		PreparationContext context) {
	return new IdTableInfoImpl(
			jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
					idTable.getQualifiedTableName(),
					jdbcServices.getJdbcEnvironment().getDialect()
			),
			buildIdTableCreateStatement( idTable, jdbcServices, metadata ),
			buildIdTableDropStatement( idTable, jdbcServices )
	);
}
 
Example #2
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked" })
public void addUniqueConstraints(Table table, List uniqueConstraints) {
	List<UniqueConstraintHolder> constraintHolders = new ArrayList<>(
			CollectionHelper.determineProperSizing( uniqueConstraints.size() )
	);

	int keyNameBase = determineCurrentNumberOfUniqueConstraintHolders( table );
	for ( String[] columns : ( List<String[]> ) uniqueConstraints ) {
		final String keyName = "key" + keyNameBase++;
		constraintHolders.add(
				new UniqueConstraintHolder().setName( keyName ).setColumns( columns )
		);
	}
	addUniqueConstraintHolders( table, constraintHolders );
}
 
Example #3
Source File: Mappings.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Table addDenormalizedTable(
		String schema, 
		String catalog, 
		String name,
		boolean isAbstract, 
		String subselect,
		Table includedTable)
throws MappingException {
       String key = subselect==null ?
       		Table.qualify(catalog, schema, name) :
       		subselect;
	if ( tables.containsKey(key) ) {
		throw new DuplicateMappingException("table", name);
	}
	
	Table table = new DenormalizedTable(includedTable);
	table.setAbstract(isAbstract);
	table.setName(name);
	table.setSchema(schema);
	table.setCatalog(catalog);
	table.setSubselect(subselect);
	tables.put(key, table);
	return table;
}
 
Example #4
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static void bindDiscriminatorProperty(Table table, RootClass entity, Element subnode,
		Mappings mappings) {
	SimpleValue discrim = new SimpleValue( table );
	entity.setDiscriminator( discrim );
	bindSimpleValue(
			subnode,
			discrim,
			false,
			RootClass.DEFAULT_DISCRIMINATOR_COLUMN_NAME,
			mappings
		);
	if ( !discrim.isTypeSpecified() ) {
		discrim.setTypeName( "string" );
		// ( (Column) discrim.getColumnIterator().next() ).setType(type);
	}
	entity.setPolymorphic( true );
	if ( "true".equals( subnode.attributeValue( "force" ) ) )
		entity.setForceDiscriminator( true );
	if ( "false".equals( subnode.attributeValue( "insert" ) ) )
		entity.setDiscriminatorInsertable( false );
}
 
Example #5
Source File: TableDependencyTracker.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Initializes the table dependency tracker.
 *
 * @param metadata the Hibernate metadata
 * @param schemaAction the kind of schema operation being done: {CREATE or DROP}.
 */
public void initializeDependencies(Metadata metadata, Action schemaAction) {
  HashMap<Table, Table> dependencies = new HashMap<>();

  for (Table childTable : metadata.collectTableMappings()) {
    Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(childTable, metadata);
    if (interleaved != null) {
      if (schemaAction == Action.CREATE || schemaAction == Action.UPDATE) {
        // If creating tables, the parent blocks the child.
        dependencies.put(childTable, SchemaUtils.getTable(interleaved.parentEntity(), metadata));
      } else {
        // If dropping tables, the child blocks the parent.
        dependencies.put(SchemaUtils.getTable(interleaved.parentEntity(), metadata), childTable);
      }
    }
  }

  this.tableDependencies = dependencies;
  this.processedTables = new HashSet<>();
}
 
Example #6
Source File: SpannerTableStatements.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Generates the statements needed to create a table.
 */
public List<String> createTable(Table table, Metadata metadata) {
  if (spannerDatabaseInfo.getAllTables().contains(table.getName())) {
    return Collections.EMPTY_LIST;
  }

  Iterable<Column> keyColumns;

  if (table.hasPrimaryKey()) {
    // a typical table that corresponds to an entity type
    keyColumns = getSortedPkColumns(table, metadata);
  } else if (isElementCollection(table, metadata)) {
    // a table that is actually an element collection property
    keyColumns = table::getColumnIterator;
  } else {
    // the case corresponding to a sequence-table that will only have 1 row.
    keyColumns = Collections.emptyList();
  }

  return getCreateTableStrings(table, metadata, keyColumns);
}
 
Example #7
Source File: SpannerTableStatements.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static List<Column> getSortedPkColumns(Table table, Metadata metadata) {
  Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(table, metadata);
  if (interleaved == null) {
    return table.getPrimaryKey().getColumns();
  }

  Table parentTable = SchemaUtils.getTable(interleaved.parentEntity(), metadata);

  List<Column> sortedParentPkColumns = getSortedPkColumns(parentTable, metadata);
  List<Column> sortedCurrentPkColumns = table.getPrimaryKey().getColumns().stream()
      .filter(column -> !sortedParentPkColumns.contains(column))
      .collect(Collectors.toList());

  ArrayList<Column> currentPkColumns = new ArrayList<>();
  currentPkColumns.addAll(sortedParentPkColumns);
  currentPkColumns.addAll(sortedCurrentPkColumns);
  return currentPkColumns;
}
 
Example #8
Source File: ComponentPropertyHolder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void addProperty(Property prop, Ejb3Column[] columns, XClass declaringClass) {
	//Ejb3Column.checkPropertyConsistency( ); //already called earlier
	/*
	 * Check table matches between the component and the columns
	 * if not, change the component table if no properties are set
	 * if a property is set already the core cannot support that
	 */
	if (columns != null) {
		Table table = columns[0].getTable();
		if ( !table.equals( component.getTable() ) ) {
			if ( component.getPropertySpan() == 0 ) {
				component.setTable( table );
			}
			else {
				throw new AnnotationException(
						"A component cannot hold properties split into 2 different tables: "
								+ this.getPath()
				);
			}
		}
	}
	addProperty( prop, declaringClass );
}
 
Example #9
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private org.hibernate.annotations.Table findMatchingComplimentTableAnnotation(Join join) {
	String tableName = join.getTable().getQuotedName();
	org.hibernate.annotations.Table table = annotatedClass.getAnnotation( org.hibernate.annotations.Table.class );
	org.hibernate.annotations.Table matchingTable = null;
	if ( table != null && tableName.equals( table.appliesTo() ) ) {
		matchingTable = table;
	}
	else {
		Tables tables = annotatedClass.getAnnotation( Tables.class );
		if ( tables != null ) {
			for (org.hibernate.annotations.Table current : tables.value()) {
				if ( tableName.equals( current.appliesTo() ) ) {
					matchingTable = current;
					break;
				}
			}
		}
	}
	return matchingTable;
}
 
Example #10
Source File: MetadataTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
 
Example #11
Source File: PersistentTableBulkIdStrategy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected IdTableInfoImpl buildIdTableInfo(
		PersistentClass entityBinding,
		Table idTable,
		JdbcServices jdbcServices,
		MetadataImplementor metadata,
		PreparationContextImpl context) {
	final String renderedName = jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
			idTable.getQualifiedTableName(),
			jdbcServices.getJdbcEnvironment().getDialect()
	);

	context.creationStatements.add( buildIdTableCreateStatement( idTable, jdbcServices, metadata ) );
	if ( dropIdTables ) {
		context.dropStatements.add( buildIdTableDropStatement( idTable, jdbcServices ) );
	}

	return new IdTableInfoImpl( renderedName );
}
 
Example #12
Source File: GroupedSchemaValidatorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void validateTables(
		Metadata metadata,
		DatabaseInformation databaseInformation,
		ExecutionOptions options,
		Dialect dialect, Namespace namespace) {

	final NameSpaceTablesInformation tables = databaseInformation.getTablesInformation( namespace );
	for ( Table table : namespace.getTables() ) {
		if ( schemaFilter.includeTable( table ) && table.isPhysicalTable() ) {
			validateTable(
					table,
					tables.getTableInformation( table ),
					metadata,
					options,
					dialect
			);
		}
	}
}
 
Example #13
Source File: IndividuallySchemaValidatorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void validateTables(
		Metadata metadata,
		DatabaseInformation databaseInformation,
		ExecutionOptions options,
		Dialect dialect,
		Namespace namespace) {
	for ( Table table : namespace.getTables() ) {
		if ( schemaFilter.includeTable( table ) && table.isPhysicalTable() ) {
			final TableInformation tableInformation = databaseInformation.getTableInformation(
					table.getQualifiedTableName()
			);
			validateTable( table, tableInformation, metadata, options, dialect );
		}
	}
}
 
Example #14
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String determineTableName(Table table, JdbcEnvironment jdbcEnvironment) {
	if ( table.getSubselect() != null ) {
		return "( " + table.getSubselect() + " )";
	}

	return jdbcEnvironment.getQualifiedObjectNameFormatter().format(
			table.getQualifiedTableName(),
			jdbcEnvironment.getDialect()
	);
}
 
Example #15
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void bindVersioningProperty(Table table, Element subnode, Mappings mappings,
		String name, RootClass entity, java.util.Map inheritedMetas) {

	String propertyName = subnode.attributeValue( "name" );
	SimpleValue val = new SimpleValue( table );
	bindSimpleValue( subnode, val, false, propertyName, mappings );
	if ( !val.isTypeSpecified() ) {
		// this is either a <version/> tag with no type attribute,
		// or a <timestamp/> tag
		if ( "version".equals( name ) ) {
			val.setTypeName( "integer" );
		}
		else {
			if ( "db".equals( subnode.attributeValue( "source" ) ) ) {
				val.setTypeName( "dbtimestamp" );
			}
			else {
				val.setTypeName( "timestamp" );
			}
		}
	}
	Property prop = new Property();
	prop.setValue( val );
	bindProperty( subnode, prop, mappings, inheritedMetas );
	// for version properties marked as being generated, make sure they are "always"
	// generated; aka, "insert" is invalid; this is dis-allowed by the DTD,
	// but just to make sure...
	if ( prop.getGeneration() == PropertyGeneration.INSERT ) {
		throw new MappingException( "'generated' attribute cannot be 'insert' for versioning property" );
	}
	makeVersion( subnode, val );
	entity.setVersion( prop );
	entity.addProperty( prop );
}
 
Example #16
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Binds a value for the specified parameters to the meta model.
 *
 * @param type        The type of the property
 * @param simpleValue The simple value instance
 * @param nullable    Whether it is nullable
 * @param columnName  The property name
 * @param mappings    The mappings
 */
protected void bindSimpleValue(String type, SimpleValue simpleValue, boolean nullable,
                               String columnName, InFlightMetadataCollector mappings) {

    simpleValue.setTypeName(type);
    Table t = simpleValue.getTable();
    Column column = new Column();
    column.setNullable(nullable);
    column.setValue(simpleValue);
    column.setName(columnName);
    if (t != null) t.addColumn(column);

    simpleValue.addColumn(column);
}
 
Example #17
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void secondPassCompileForeignKeys(MetadataBuildingContext buildingContext) {
	int uniqueInteger = 0;
	Set<ForeignKey> done = new HashSet<>();
	for ( Table table : collectTableMappings() ) {
		table.setUniqueInteger( uniqueInteger++ );
		secondPassCompileForeignKeys( table, done, buildingContext );
	}
}
 
Example #18
Source File: StandardTableExporter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void applyComments(Table table, QualifiedName tableName, List<String> sqlStrings) {
	if ( dialect.supportsCommentOn() ) {
		if ( table.getComment() != null ) {
			sqlStrings.add( "comment on table " + tableName + " is '" + table.getComment() + "'" );
		}
		final Iterator iter = table.getColumnIterator();
		while ( iter.hasNext() ) {
			Column column = (Column) iter.next();
			String columnComment = column.getComment();
			if ( columnComment != null ) {
				sqlStrings.add( "comment on column " + tableName + '.' + column.getQuotedName( dialect ) + " is '" + columnComment + "'" );
			}
		}
	}
}
 
Example #19
Source File: AbstractSchemaValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void validateColumnType(
		Table table,
		Column column,
		ColumnInformation columnInformation,
		Metadata metadata,
		ExecutionOptions options,
		Dialect dialect) {
	boolean typesMatch = column.getSqlTypeCode( metadata ) == columnInformation.getTypeCode()
			|| column.getSqlType( dialect, metadata ).toLowerCase(Locale.ROOT).startsWith( columnInformation.getTypeName().toLowerCase(Locale.ROOT) );
	if ( !typesMatch ) {
		throw new SchemaManagementException(
				String.format(
						"Schema-validation: wrong column type encountered in column [%s] in " +
								"table [%s]; found [%s (Types#%s)], but expecting [%s (Types#%s)]",
						column.getName(),
						table.getQualifiedTableName(),
						columnInformation.getTypeName().toLowerCase(Locale.ROOT),
						JdbcTypeNameMapper.getTypeName( columnInformation.getTypeCode() ),
						column.getSqlType().toLowerCase(Locale.ROOT),
						JdbcTypeNameMapper.getTypeName( column.getSqlTypeCode( metadata ) )
				)
		);
	}

	// this is the old Hibernate check...
	//
	// but I think a better check involves checks against type code and then the type code family, not
	// just the type name.
	//
	// See org.hibernate.type.descriptor.sql.JdbcTypeFamilyInformation
	// todo : this ^^
}
 
Example #20
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Table addTable(
		String schemaName,
		String catalogName,
		String name,
		String subselectFragment,
		boolean isAbstract) {
	final Namespace namespace = getDatabase().locateNamespace(
			getDatabase().toIdentifier( catalogName ),
			getDatabase().toIdentifier( schemaName )
	);

	// annotation binding depends on the "table name" for @Subselect bindings
	// being set into the generated table (mainly to avoid later NPE), but for now we need to keep that :(
	final Identifier logicalName;
	if ( name != null ) {
		logicalName = getDatabase().toIdentifier( name );
	}
	else {
		logicalName = null;
	}

	if ( subselectFragment != null ) {
		return new Table( namespace, logicalName, subselectFragment, isAbstract );
	}
	else {
		Table table = namespace.locateTable( logicalName );
		if ( table != null ) {
			if ( !isAbstract ) {
				table.setAbstract( false );
			}
			return table;
		}
		return namespace.createTable( logicalName, isAbstract );
	}
}
 
Example #21
Source File: Configuration.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 );
		}
	}
}
 
Example #22
Source File: IgniteCacheInitializer.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Create indexes for {@code @Index} annotations
 * @param queryEntity
 * @param context
 */
private void addUserIndexes(QueryEntity queryEntity, SchemaDefinitionContext context, String tableName) {
	Namespace namespace = context.getDatabase().getDefaultNamespace();
	Optional<Table> tableOptional = namespace.getTables().stream().filter( currentTable -> currentTable.getName().equals( tableName ) ).findFirst();
	if ( tableOptional.isPresent() ) {
		Table table = tableOptional.get();
		for ( Iterator<Index> indexIterator = table.getIndexIterator(); indexIterator.hasNext(); ) {
			Index index = indexIterator.next();
			appendIndex( queryEntity, index, context );
		}
	}
}
 
Example #23
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void processUniqueConstraintHolders(MetadataBuildingContext buildingContext) {
	if ( uniqueConstraintHoldersByTable == null ) {
		return;
	}

	for ( Map.Entry<Table, List<UniqueConstraintHolder>> tableListEntry : uniqueConstraintHoldersByTable.entrySet() ) {
		final Table table = tableListEntry.getKey();
		final List<UniqueConstraintHolder> uniqueConstraints = tableListEntry.getValue();
		for ( UniqueConstraintHolder holder : uniqueConstraints ) {
			buildUniqueKeyFromColumnNames( table, holder.getName(), holder.getColumns(), buildingContext );
		}
	}

	uniqueConstraintHoldersByTable.clear();
}
 
Example #24
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 #25
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void bindIndex(Attribute indexAttribute, Table table, Column column, Mappings mappings) {
	if ( indexAttribute != null && table != null ) {
		StringTokenizer tokens = new StringTokenizer( indexAttribute.getValue(), ", " );
		while ( tokens.hasMoreTokens() ) {
			table.getOrCreateIndex( tokens.nextToken() ).addColumn( column );
		}
	}
}
 
Example #26
Source File: TableBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static Table buildAndFillTable(
		String schema,
		String catalog,
		ObjectNameSource nameSource,
		NamingStrategyHelper namingStrategyHelper,
		boolean isAbstract,
		List<UniqueConstraintHolder> uniqueConstraints,
		List<JPAIndexHolder> jpaIndexHolders,
		String constraints,
		MetadataBuildingContext buildingContext,
		String subselect,
		InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) {
	final Identifier logicalName;
	if ( StringHelper.isNotEmpty( nameSource.getExplicitName() ) ) {
		logicalName = namingStrategyHelper.handleExplicitName( nameSource.getExplicitName(), buildingContext );
	}
	else {
		logicalName = namingStrategyHelper.determineImplicitName( buildingContext );
	}

	return buildAndFillTable(
			schema,
			catalog,
			logicalName,
			isAbstract,
			uniqueConstraints,
			jpaIndexHolders,
			constraints,
			buildingContext,
			subselect,
			denormalizedSuperTableXref
	);
}
 
Example #27
Source File: AbstractSchemaMigrator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void applyForeignKeys(
		Table table,
		TableInformation tableInformation,
		Dialect dialect,
		Metadata metadata,
		Formatter formatter,
		ExecutionOptions options,
		GenerationTarget... targets) {
	if ( dialect.hasAlterTable() ) {
		final Exporter<ForeignKey> exporter = dialect.getForeignKeyExporter();

		@SuppressWarnings("unchecked")
		final Iterator<ForeignKey> fkItr = table.getForeignKeyIterator();
		while ( fkItr.hasNext() ) {
			final ForeignKey foreignKey = fkItr.next();
			if ( foreignKey.isPhysicalConstraint() && foreignKey.isCreationEnabled() ) {
				boolean existingForeignKeyFound = false;
				if ( tableInformation != null ) {
					existingForeignKeyFound = checkForExistingForeignKey(
							foreignKey,
							tableInformation
					);
				}
				if ( !existingForeignKeyFound ) {
					// todo : shouldn't we just drop+recreate if FK exists?
					//		this follows the existing code from legacy SchemaUpdate which just skipped

					// in old SchemaUpdate code, this was the trigger to "create"
					applySqlStrings(
							false,
							exporter.getSqlCreateStrings( foreignKey, metadata ),
							formatter,
							options,
							targets
					);
				}
			}
		}
	}
}
 
Example #28
Source File: AbstractMultiTableBulkIdStrategyImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected String buildIdTableCreateStatement(Table idTable, JdbcServices jdbcServices, MetadataImplementor metadata) {
	final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
	final Dialect dialect = jdbcEnvironment.getDialect();

	StringBuilder buffer = new StringBuilder( getIdTableSupport().getCreateIdTableCommand() )
			.append( ' ' )
			.append( jdbcEnvironment.getQualifiedObjectNameFormatter().format( idTable.getQualifiedTableName(), dialect ) )
			.append( " (" );

	Iterator itr = idTable.getColumnIterator();
	while ( itr.hasNext() ) {
		final Column column = (Column) itr.next();
		buffer.append( column.getQuotedName( dialect ) ).append( ' ' );
		buffer.append( column.getSqlType( dialect, metadata ) );
		if ( column.isNullable() ) {
			buffer.append( dialect.getNullColumnString() );
		}
		else {
			buffer.append( " not null" );
		}
		if ( itr.hasNext() ) {
			buffer.append( ", " );
		}
	}

	buffer.append( ") " );
	if ( getIdTableSupport().getCreateIdTableStatementOptions() != null ) {
		buffer.append( getIdTableSupport().getCreateIdTableStatementOptions() );
	}

	return buffer.toString();
}
 
Example #29
Source File: HibernatePropertyParser.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 构造SimpleValue
 */
private SimpleValue buildSimpleValue(Table table, String type,
									 String columnName, int len) {
	SimpleValue value = new SimpleValue(metadataCollector, table);
	String typeName = null;
	for (Entry<String, String> entry : HBMTYPES.entrySet()) {
		if (entry.getValue().equals(type)) {
			typeName = entry.getKey();
			break;
		}
	}
	value.setTypeName(typeName == null ? type.toLowerCase() : typeName);
	buildColumn(columnName, len, value, table);
	return value;
}
 
Example #30
Source File: IncrementGenerator.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 dialect)
throws MappingException {

	String tableList = params.getProperty("tables");
	if (tableList==null) tableList = params.getProperty(PersistentIdentifierGenerator.TABLES);
	String[] tables = StringHelper.split(", ", tableList);
	String column = params.getProperty("column");
	if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK);
	String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
	String catalog = params.getProperty(PersistentIdentifierGenerator.CATALOG);
	returnClass = type.getReturnedClass();
	

	StringBuffer buf = new StringBuffer();
	for ( int i=0; i<tables.length; i++ ) {
		if (tables.length>1) {
			buf.append("select ").append(column).append(" from ");
		}
		buf.append( Table.qualify( catalog, schema, tables[i] ) );
		if ( i<tables.length-1) buf.append(" union ");
	}
	if (tables.length>1) {
		buf.insert(0, "( ").append(" ) ids_");
		column = "ids_." + column;
	}
	
	sql = "select max(" + column + ") from " + buf.toString();
}