下面列出了怎么用org.hibernate.mapping.Table的API类实例代码及写法,或者点击链接到github查看源代码。
@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 );
}
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 );
}
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;
}
/**
* 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<>();
}
/**
* 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);
}
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;
}
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 );
}
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;
}
@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 );
}
@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
);
}
}
}
@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 );
}
}
}
@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 )
);
}
@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()
);
}
}
}
}
/**
* 构造SimpleValue
*/
private SimpleValue buildSimpleValue(Table table, PersistentClass pclazz,
MetaProperty property, String columnName) {
// 是否枚举是枚举类型
if (MetaConstant.isEnum(property)) {
Class<?>[] inners = ReflectUtil
.classForName(property.getEnumClass()).getClasses();
if (inners != null) {
for (Class<?> inner : inners) {
if (!AttributeConverter.class.isAssignableFrom(inner)) {
continue;
}
SimpleValue value = new SimpleValue(metadataCollector,
table);
value.setTypeName(StringHelper.join(
AttributeConverterTypeAdapter.NAME_PREFIX,
inner.getName()));
value.setTypeUsingReflection(pclazz.getClassName(),
property.getName());
buildColumn(columnName, property.getLength(), value, table);
return value;
}
}
}
return buildSimpleValue(table, property.getType(), columnName,
property.getLength());
}
/**
* 构造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;
}
@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 );
}
}
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 );
}
}
}
/**
* 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 );
}
}
}
@Test
public void testDatabaseMetadata() {
for(Namespace namespace : MetadataExtractorIntegrator.INSTANCE.getDatabase().getNamespaces()) {
for( Table table : namespace.getTables()) {
LOGGER.info( "Table {} has the following columns: {}",
table,
StreamSupport.stream(
Spliterators.spliteratorUnknownSize( table.getColumnIterator(), Spliterator.ORDERED), false)
.collect( Collectors.toList()) );
}
}
}
protected String getJoinedSubClassTableName(
HibernatePersistentEntity sub, PersistentClass model, Table denormalizedSuperTable,
InFlightMetadataCollector mappings, String sessionFactoryBeanName) {
String logicalTableName = unqualify(model.getEntityName());
String physicalTableName = getTableName(sub, sessionFactoryBeanName);
String schemaName = getSchemaName(mappings);
String catalogName = getCatalogName(mappings);
mappings.addTableNameBinding(schemaName, catalogName, logicalTableName, physicalTableName, denormalizedSuperTable);
return physicalTableName;
}
/**
* Generates the statements needed to drop a table.
*/
public List<String> dropTable(Table table) {
ArrayList<String> dropStrings = new ArrayList<>();
for (String indexName : getTableIndices(table)) {
if (spannerDatabaseInfo.getAllIndices().contains(indexName)) {
dropStrings.add("drop index " + indexName);
}
}
if (spannerDatabaseInfo.getAllTables().contains(table.getName())) {
dropStrings.add(this.spannerDialect.getDropTableString(table.getQuotedName()));
}
return dropStrings;
}
/**
* Returns true if a table is generated by a Hibernate element collection.
*/
private boolean isElementCollection(Table table, Metadata metadata) {
for (Collection collection : metadata.getCollectionBindings()) {
if (collection.getCollectionTable().equals(table)) {
return true;
}
}
return false;
}
protected void secondPassCompileForeignKeys(Table table, Set done) throws MappingException {
table.createForeignKeys();
Iterator iter = table.getForeignKeyIterator();
while ( iter.hasNext() ) {
ForeignKey fk = (ForeignKey) iter.next();
if ( !done.contains( fk ) ) {
done.add( fk );
final String referencedEntityName = fk.getReferencedEntityName();
if ( referencedEntityName == null ) {
throw new MappingException(
"An association from the table " +
fk.getTable().getName() +
" does not specify the referenced entity"
);
}
if ( log.isDebugEnabled() ) {
log.debug( "resolving reference to class: " + referencedEntityName );
}
PersistentClass referencedClass = (PersistentClass) classes.get( referencedEntityName );
if ( referencedClass == null ) {
throw new MappingException(
"An association from the table " +
fk.getTable().getName() +
" refers to an unmapped class: " +
referencedEntityName
);
}
if ( referencedClass.isJoinedSubclass() ) {
secondPassCompileForeignKeys( referencedClass.getSuperclass().getTable(), done );
}
fk.setReferencedTable( referencedClass.getTable() );
fk.alignColumns();
}
}
}
private static String getInterleavedClause(Table table, Metadata metadata) {
Interleaved interleaved = SchemaUtils.getInterleaveAnnotation(table, metadata);
if (interleaved != null) {
Table parentTable = SchemaUtils.getTable(interleaved.parentEntity(), metadata);
String interleaveClause = ", INTERLEAVE IN PARENT " + parentTable.getQuotedName();
if (interleaved.cascadeDelete()) {
interleaveClause += " ON DELETE CASCADE";
}
return interleaveClause;
}
return "";
}
@Test
public void givenDefaultBootNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
String entity = Account.class.getCanonicalName();
PersistentClass persistentClass = metadata.getEntityBinding(entity);
Table table = persistentClass.getTable();
String physicalNameExpected = "secondary_email";
String implicitNameExpected = "default_email";
String tableNameExpected = "account";
String tableNameCreated = table.getName();
String physicalNameCreated = table
.getColumn(3)
.getName();
String implicitNameCreated = table
.getColumn(2)
.getName();
SoftAssertions softly = new SoftAssertions();
softly
.assertThat(tableNameCreated)
.isEqualTo(tableNameExpected);
softly
.assertThat(physicalNameCreated)
.isEqualTo(physicalNameExpected);
softly
.assertThat(implicitNameCreated)
.isEqualTo(implicitNameExpected);
softly.assertAll();
}
@Test
public void testDropTableStatement_missingTable() {
Table table = new Table();
table.setName("Missing_Table");
List<String> statements = spannerTableStatements.dropTable(table);
assertThat(statements).isEmpty();
}
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
identifierType = type;
boolean forceTableUse = PropertiesHelper.getBoolean( FORCE_TBL_PARAM, params, false );
String sequenceName = PropertiesHelper.getString( SEQUENCE_PARAM, params, DEF_SEQUENCE_NAME );
if ( sequenceName.indexOf( '.' ) < 0 ) {
String schemaName = params.getProperty( SCHEMA );
String catalogName = params.getProperty( CATALOG );
sequenceName = Table.qualify( catalogName, schemaName, sequenceName );
}
int initialValue = PropertiesHelper.getInt( INITIAL_PARAM, params, DEFAULT_INITIAL_VALUE );
int incrementSize = PropertiesHelper.getInt( INCREMENT_PARAM, params, DEFAULT_INCREMENT_SIZE );
String valueColumnName = PropertiesHelper.getString( VALUE_COLUMN_PARAM, params, DEF_VALUE_COLUMN );
String defOptStrategy = incrementSize <= 1 ? OptimizerFactory.NONE : OptimizerFactory.POOL;
String optimizationStrategy = PropertiesHelper.getString( OPT_PARAM, params, defOptStrategy );
if ( OptimizerFactory.NONE.equals( optimizationStrategy ) && incrementSize > 1 ) {
log.warn( "config specified explicit optimizer of [" + OptimizerFactory.NONE + "], but [" + INCREMENT_PARAM + "=" + incrementSize + "; honoring optimizer setting" );
incrementSize = 1;
}
if ( dialect.supportsSequences() && !forceTableUse ) {
if ( OptimizerFactory.POOL.equals( optimizationStrategy ) && !dialect.supportsPooledSequences() ) {
// TODO : may even be better to fall back to a pooled table strategy here so that the db stored values remain consistent...
optimizationStrategy = OptimizerFactory.HILO;
}
databaseStructure = new SequenceStructure( dialect, sequenceName, initialValue, incrementSize );
}
else {
databaseStructure = new TableStructure( dialect, sequenceName, valueColumnName, initialValue, incrementSize );
}
optimizer = OptimizerFactory.buildOptimizer( optimizationStrategy, identifierType.getReturnedClass(), incrementSize );
databaseStructure.prepare( optimizer );
}
/**
* Build an index
*/
public IndexOrUniqueKeySecondPass(Table table, String indexName, String[] columns, MetadataBuildingContext buildingContext) {
this.table = table;
this.indexName = indexName;
this.columns = columns;
this.buildingContext = buildingContext;
this.column = null;
this.unique = false;
}
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();
}
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
);
}