diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/RevengMetadataCollector.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/RevengMetadataCollector.java index b3809d1f74..b467b424bc 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/RevengMetadataCollector.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/RevengMetadataCollector.java @@ -32,85 +32,86 @@ public class RevengMetadataCollector { - private MetadataBuildingContext metadataBuildingContext = null; - private final Map tables; - private Map> oneToManyCandidates; - private final Map suggestedIdentifierStrategies; - - public RevengMetadataCollector(MetadataBuildingContext metadataBuildingContext) { - this(); - this.metadataBuildingContext = metadataBuildingContext; - } - - public RevengMetadataCollector() { - this.tables = new HashMap(); - this.suggestedIdentifierStrategies = new HashMap(); - } - - public Iterator iterateTables() { - return tables.values().iterator(); - } - - // TableIdentifier's catalog, schema and name should be quoted - public Table addTable(TableIdentifier tableIdentifier) { - Table result = null; - String catalog = tableIdentifier.getCatalog(); - String schema = tableIdentifier.getSchema(); - String name = tableIdentifier.getName(); - InFlightMetadataCollector metadataCollector = getMetadataCollector(); - if (metadataCollector != null) { - result = metadataCollector.addTable(schema, catalog, name, null, false, metadataBuildingContext); - } else { - result = createTable(catalog, schema, name); - } - if (tables.containsKey(tableIdentifier)) { - throw new RuntimeException( - "Attempt to add a double entry for table: " + - TableNameQualifier.qualify(catalog, schema, name)); - } - tables.put(tableIdentifier, result); - return result; - } - - public Table getTable(TableIdentifier tableIdentifier) { - return tables.get(tableIdentifier); - } - - public Collection
getTables() { - return tables.values(); - } - - public void setOneToManyCandidates(Map> oneToManyCandidates) { - this.oneToManyCandidates = oneToManyCandidates; - } - - public Map> getOneToManyCandidates() { - return oneToManyCandidates; - } - - public String getSuggestedIdentifierStrategy(String catalog, String schema, String name) { - return (String) suggestedIdentifierStrategies.get(TableIdentifier.create(catalog, schema, name)); - } - - public void addSuggestedIdentifierStrategy(String catalog, String schema, String name, String idstrategy) { - suggestedIdentifierStrategies.put(TableIdentifier.create(catalog, schema, name), idstrategy); - } - - private Table createTable(String catalog, String schema, String name) { - Table table = new Table("Hibernate Tools"); - table.setAbstract(false); - table.setName(name); - table.setSchema(schema); - table.setCatalog(catalog); - return table; - } - - private InFlightMetadataCollector getMetadataCollector() { - InFlightMetadataCollector result = null; - if (metadataBuildingContext != null) { - result = metadataBuildingContext.getMetadataCollector(); - } - return result; - } - + private MetadataBuildingContext metadataBuildingContext = null; + private final Map tables; + private Map> oneToManyCandidates; + private final Map suggestedIdentifierStrategies; + + public RevengMetadataCollector(MetadataBuildingContext metadataBuildingContext) { + this(); + this.metadataBuildingContext = metadataBuildingContext; + } + + public RevengMetadataCollector() { + this.tables = new HashMap<>(); + this.suggestedIdentifierStrategies = new HashMap<>(); + } + + public Iterator
iterateTables() { + return tables.values().iterator(); + } + + // TableIdentifier's catalog, schema and name should be quoted + public Table addTable(TableIdentifier tableIdentifier) { + Table result; + String catalog = tableIdentifier.getCatalog(); + String schema = tableIdentifier.getSchema(); + String name = tableIdentifier.getName(); + InFlightMetadataCollector metadataCollector = getMetadataCollector(); + if (metadataCollector != null) { + result = metadataCollector.addTable(schema, catalog, name, null, false, metadataBuildingContext); + } + else { + result = createTable(catalog, schema, name); + } + if (tables.containsKey(tableIdentifier)) { + throw new RuntimeException( + "Attempt to add a double entry for table: " + + TableNameQualifier.qualify(catalog, schema, name)); + } + tables.put(tableIdentifier, result); + return result; + } + + public Table getTable(TableIdentifier tableIdentifier) { + return tables.get(tableIdentifier); + } + + public Collection
getTables() { + return tables.values(); + } + + public void setOneToManyCandidates(Map> oneToManyCandidates) { + this.oneToManyCandidates = oneToManyCandidates; + } + + public Map> getOneToManyCandidates() { + return oneToManyCandidates; + } + + public String getSuggestedIdentifierStrategy(String catalog, String schema, String name) { + return suggestedIdentifierStrategies.get(TableIdentifier.create(catalog, schema, name)); + } + + public void addSuggestedIdentifierStrategy(String catalog, String schema, String name, String idstrategy) { + suggestedIdentifierStrategies.put(TableIdentifier.create(catalog, schema, name), idstrategy); + } + + private Table createTable(String catalog, String schema, String name) { + Table table = new Table("Hibernate Tools"); + table.setAbstract(false); + table.setName(name); + table.setSchema(schema); + table.setCatalog(catalog); + return table; + } + + private InFlightMetadataCollector getMetadataCollector() { + InFlightMetadataCollector result = null; + if (metadataBuildingContext != null) { + result = metadataBuildingContext.getMetadataCollector(); + } + return result; + } + } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/AbstractStrategy.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/AbstractStrategy.java index 1e74c012ba..317ea4ef2c 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/AbstractStrategy.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/AbstractStrategy.java @@ -44,310 +44,316 @@ public abstract class AbstractStrategy implements RevengStrategy { - static final private Logger log = Logger.getLogger(AbstractStrategy.class); - - private static final Set AUTO_OPTIMISTICLOCK_COLUMNS; - - private RevengSettings settings = new RevengSettings(this); - - static { - AUTO_OPTIMISTICLOCK_COLUMNS = new HashSet(); - AUTO_OPTIMISTICLOCK_COLUMNS.add("version"); - AUTO_OPTIMISTICLOCK_COLUMNS.add("timestamp"); - AUTO_OPTIMISTICLOCK_COLUMNS.add("dbtimestamp"); - } - - - public AbstractStrategy() { - super(); - } - - public String columnToPropertyName(TableIdentifier table, String columnName) { - String decapitalize = Introspector.decapitalize( toUpperCamelCase(columnName) ); - - return keywordCheck( decapitalize ); - } - - private String keywordCheck(String possibleKeyword) { - if(NameConverter.isReservedJavaKeyword(possibleKeyword)) { - possibleKeyword = possibleKeyword + "_"; - } - return possibleKeyword; - } - - protected String toUpperCamelCase(String s) { - return NameConverter.toUpperCamelCase(s); - } - - /** - * Does some crude english pluralization - * TODO: are the from/to names correct ? - */ + static final private Logger log = Logger.getLogger(AbstractStrategy.class); + + private static final Set AUTO_OPTIMISTICLOCK_COLUMNS; + + private RevengSettings settings = new RevengSettings(this); + + static { + AUTO_OPTIMISTICLOCK_COLUMNS = new HashSet<>(); + AUTO_OPTIMISTICLOCK_COLUMNS.add("version"); + AUTO_OPTIMISTICLOCK_COLUMNS.add("timestamp"); + AUTO_OPTIMISTICLOCK_COLUMNS.add("dbtimestamp"); + } + + + public AbstractStrategy() { + super(); + } + + public String columnToPropertyName(TableIdentifier table, String columnName) { + String decapitalize = Introspector.decapitalize( toUpperCamelCase(columnName) ); + + return keywordCheck( decapitalize ); + } + + private String keywordCheck(String possibleKeyword) { + if(NameConverter.isReservedJavaKeyword(possibleKeyword)) { + possibleKeyword = possibleKeyword + "_"; + } + return possibleKeyword; + } + + protected String toUpperCamelCase(String s) { + return NameConverter.toUpperCamelCase(s); + } + + /** + * Does some crude english pluralization + * TODO: are the from/to names correct ? + */ public String foreignKeyToCollectionName(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns, boolean uniqueReference) { - String propertyName = Introspector.decapitalize( StringHelper.unqualify( getRoot().tableToClassName(fromTable) ) ); - propertyName = pluralize( propertyName ); - - if(!uniqueReference) { - if(fromColumns!=null && fromColumns.size()==1) { - String columnName = ( (Column) fromColumns.get(0) ).getName(); - propertyName = propertyName + "For" + toUpperCamelCase(columnName); - } - else { // composite key or no columns at all safeguard - propertyName = propertyName + "For" + toUpperCamelCase(keyname); - } + String propertyName = Introspector.decapitalize( StringHelper.unqualify( getRoot().tableToClassName(fromTable) ) ); + propertyName = pluralize( propertyName ); + + if(!uniqueReference) { + if(fromColumns!=null && fromColumns.size()==1) { + String columnName = ( (Column) fromColumns.get(0) ).getName(); + propertyName = propertyName + "For" + toUpperCamelCase(columnName); + } + else { // composite key or no columns at all safeguard + propertyName = propertyName + "For" + toUpperCamelCase(keyname); + } } return propertyName; } - protected String pluralize(String singular) { - return NameConverter.simplePluralize(singular); - } + protected String pluralize(String singular) { + return NameConverter.simplePluralize(singular); + } + + public String foreignKeyToInverseEntityName(String keyname, + TableIdentifier fromTable, List fromColumnNames, + TableIdentifier referencedTable, List referencedColumnNames, + boolean uniqueReference) { + return foreignKeyToEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); + } + - public String foreignKeyToInverseEntityName(String keyname, - TableIdentifier fromTable, List fromColumnNames, - TableIdentifier referencedTable, List referencedColumnNames, - boolean uniqueReference) { - return foreignKeyToEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); - } - - public String foreignKeyToEntityName(String keyname, TableIdentifier fromTable, List fromColumnNames, TableIdentifier referencedTable, List referencedColumnNames, boolean uniqueReference) { String propertyName = Introspector.decapitalize( StringHelper.unqualify( getRoot().tableToClassName(referencedTable) ) ); - + if(!uniqueReference) { - if(fromColumnNames!=null && fromColumnNames.size()==1) { - String columnName = ( (Column) fromColumnNames.get(0) ).getName(); - propertyName = propertyName + "By" + toUpperCamelCase(columnName); - } - else { // composite key or no columns at all safeguard - propertyName = propertyName + "By" + toUpperCamelCase(keyname); - } + if(fromColumnNames!=null && fromColumnNames.size()==1) { + String columnName = ( (Column) fromColumnNames.get(0) ).getName(); + propertyName = propertyName + "By" + toUpperCamelCase(columnName); + } + else { // composite key or no columns at all safeguard + propertyName = propertyName + "By" + toUpperCamelCase(keyname); + } } - + return propertyName; } - - public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { - String preferredHibernateType = JdbcToHibernateTypeHelper.getPreferredHibernateType(sqlType, length, precision, scale, nullable, generatedIdentifier); - - String location = ""; - if(log.isDebugEnabled()) { - String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; - if(table!=null) { - location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName + info; - } else { - - location += " Column: " + columnName + info; - } - } - if(preferredHibernateType==null) { - log.debug("No default type found for [" + location + "] falling back to [serializable]"); - return "serializable"; - } else { - log.debug("Default type found for [" + location + "] to [" + preferredHibernateType + "]"); - return preferredHibernateType; - } - } - - public boolean excludeTable(TableIdentifier ti) { - return false; - } - - public boolean excludeColumn(TableIdentifier identifier, String columnName) { - return false; - } - - public String tableToClassName(TableIdentifier tableIdentifier) { - - String pkgName = settings.getDefaultPackageName(); - String className = toUpperCamelCase( tableIdentifier.getName() ); - - if(!pkgName.isEmpty()) { - return StringHelper.qualify(pkgName, className); - } - else { - return className; - } - - } - - public List getForeignKeys(TableIdentifier referencedTable) { - return Collections.emptyList(); - } - - public String getTableIdentifierStrategyName(TableIdentifier identifier) { - return null; - } - - public Properties getTableIdentifierProperties(TableIdentifier identifier) { - return new Properties(); - } - - public List getPrimaryKeyColumnNames(TableIdentifier identifier) { - return null; - } - - public String classNameToCompositeIdName(String className) { - return className + "Id"; - } - - public void close() { - - } - - - - /** Return explicit which column name should be used for optimistic lock */ - public String getOptimisticLockColumnName(TableIdentifier identifier) { - return null; - } - - public boolean useColumnForOptimisticLock(TableIdentifier identifier, String column) { - if(settings.getDetectOptimsticLock()) { - return AUTO_OPTIMISTICLOCK_COLUMNS.contains(column.toLowerCase()); - } else { - return false; - } - } - - public List getSchemaSelections() { - return null; - } - - public String tableToIdentifierPropertyName(TableIdentifier tableIdentifier) { - return null; - } - - public String tableToCompositeIdName(TableIdentifier identifier) { - return null; - } - - public boolean excludeForeignKeyAsCollection(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns) { - return !settings.createCollectionForForeignKey(); - } - - public boolean excludeForeignKeyAsManytoOne(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns) { - return !settings.createManyToOneForForeignKey(); - } - - public boolean isForeignKeyCollectionInverse(String name, Table foreignKeyTable, List columns, Table foreignKeyReferencedTable, List referencedColumns) { - if(foreignKeyTable==null) { - return true; // we don't know better - } - if(isManyToManyTable(foreignKeyTable)) { - // if the reference column is the first one then we are inverse. - Column column = foreignKeyTable.getColumn(0); - Column fkColumn = (Column) referencedColumns.get(0); + + public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { + String preferredHibernateType = JdbcToHibernateTypeHelper.getPreferredHibernateType(sqlType, length, precision, scale, nullable, generatedIdentifier); + + String location = ""; + if(log.isDebugEnabled()) { + String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; + if(table!=null) { + location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName + info; + } + else { + + location += " Column: " + columnName + info; + } + } + if(preferredHibernateType==null) { + log.debug("No default type found for [" + location + "] falling back to [serializable]"); + return "serializable"; + } + else { + log.debug("Default type found for [" + location + "] to [" + preferredHibernateType + "]"); + return preferredHibernateType; + } + } + + public boolean excludeTable(TableIdentifier ti) { + return false; + } + + public boolean excludeColumn(TableIdentifier identifier, String columnName) { + return false; + } + + public String tableToClassName(TableIdentifier tableIdentifier) { + + String pkgName = settings.getDefaultPackageName(); + String className = toUpperCamelCase( tableIdentifier.getName() ); + + if(!pkgName.isEmpty()) { + return StringHelper.qualify(pkgName, className); + } + else { + return className; + } + + } + + public List getForeignKeys(TableIdentifier referencedTable) { + return Collections.emptyList(); + } + + public String getTableIdentifierStrategyName(TableIdentifier identifier) { + return null; + } + + public Properties getTableIdentifierProperties(TableIdentifier identifier) { + return new Properties(); + } + + public List getPrimaryKeyColumnNames(TableIdentifier identifier) { + return null; + } + + public String classNameToCompositeIdName(String className) { + return className + "Id"; + } + + public void close() { + + } + + + + /** Return explicit which column name should be used for optimistic lock */ + public String getOptimisticLockColumnName(TableIdentifier identifier) { + return null; + } + + public boolean useColumnForOptimisticLock(TableIdentifier identifier, String column) { + if(settings.getDetectOptimsticLock()) { + return AUTO_OPTIMISTICLOCK_COLUMNS.contains(column.toLowerCase()); + } + else { + return false; + } + } + + public List getSchemaSelections() { + return null; + } + + public String tableToIdentifierPropertyName(TableIdentifier tableIdentifier) { + return null; + } + + public String tableToCompositeIdName(TableIdentifier identifier) { + return null; + } + + public boolean excludeForeignKeyAsCollection(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns) { + return !settings.createCollectionForForeignKey(); + } + + public boolean excludeForeignKeyAsManytoOne(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns) { + return !settings.createManyToOneForForeignKey(); + } + + public boolean isForeignKeyCollectionInverse(String name, Table foreignKeyTable, List columns, Table foreignKeyReferencedTable, List referencedColumns) { + if(foreignKeyTable==null) { + return true; // we don't know better + } + if(isManyToManyTable(foreignKeyTable)) { + // if the reference column is the first one then we are inverse. + Column column = foreignKeyTable.getColumn(0); + Column fkColumn = (Column) referencedColumns.get(0); return fkColumn.equals(column); - } - return true; - } - - public boolean isForeignKeyCollectionLazy(String name, TableIdentifier foreignKeyTable, List columns, TableIdentifier foreignKeyReferencedTable, List referencedColumns) { - return true; - } - - public void setSettings(RevengSettings settings) { - this.settings = settings; - } - - public boolean isOneToOne(ForeignKey foreignKey) { - if(settings.getDetectOneToOne()) { - // add support for non-PK associations - List fkColumns = foreignKey.getColumns(); - List pkForeignTableColumns = Collections.emptyList(); - - if (foreignKey.getTable().hasPrimaryKey()) - pkForeignTableColumns = foreignKey.getTable().getPrimaryKey().getColumns(); - - boolean equals = fkColumns.size() == pkForeignTableColumns.size(); - - Iterator columns = foreignKey.getColumns().iterator(); - while (equals && columns.hasNext()) { - Column fkColumn = columns.next(); - equals = pkForeignTableColumns.contains(fkColumn); - } - return equals; - } else { - return false; - } - } - - public boolean isManyToManyTable(Table table) { - if(settings.getDetectManyToMany()) { - - // if the number of columns in the primary key is different - // than the total number of columns then it can't be a middle table - PrimaryKey pk = table.getPrimaryKey(); - if ( pk==null || pk.getColumns().size() != table.getColumnSpan() ) - return false; - - List foreignKeys = new ArrayList(); - - // if we have more than 2 fk, means we have more than 2 table implied - // in this table --> cannot be a simple many-to-many - for (ForeignKey fkey : table.getForeignKeyCollection()) { - foreignKeys.add( fkey ); - if(foreignKeys.size()>2) { - return false; // early exit if we have more than two fk. - } - } - if(foreignKeys.size()!=2) { - return false; - } - - // tests that all columns are implied in the fks + } + return true; + } + + public boolean isForeignKeyCollectionLazy(String name, TableIdentifier foreignKeyTable, List columns, TableIdentifier foreignKeyReferencedTable, List referencedColumns) { + return true; + } + + public void setSettings(RevengSettings settings) { + this.settings = settings; + } + + public boolean isOneToOne(ForeignKey foreignKey) { + if(settings.getDetectOneToOne()) { + // add support for non-PK associations + List fkColumns = foreignKey.getColumns(); + List pkForeignTableColumns = Collections.emptyList(); + + if (foreignKey.getTable().hasPrimaryKey()) + pkForeignTableColumns = foreignKey.getTable().getPrimaryKey().getColumns(); + + boolean equals = fkColumns.size() == pkForeignTableColumns.size(); + + Iterator columns = foreignKey.getColumns().iterator(); + while (equals && columns.hasNext()) { + Column fkColumn = columns.next(); + equals = pkForeignTableColumns.contains(fkColumn); + } + + return equals; + } + else { + return false; + } + } + + public boolean isManyToManyTable(Table table) { + if(settings.getDetectManyToMany()) { + + // if the number of columns in the primary key is different + // than the total number of columns then it can't be a middle table + PrimaryKey pk = table.getPrimaryKey(); + if ( pk==null || pk.getColumns().size() != table.getColumnSpan() ) + return false; + + List foreignKeys = new ArrayList<>(); + + // if we have more than 2 fk, means we have more than 2 table implied + // in this table --> cannot be a simple many-to-many + for (ForeignKey fkey : table.getForeignKeyCollection()) { + foreignKeys.add( fkey ); + if(foreignKeys.size()>2) { + return false; // early exit if we have more than two fk. + } + } + if(foreignKeys.size()!=2) { + return false; + } + + // tests that all columns are implied in the fks Set columns = new HashSet<>(table.getColumns()); - - for (ForeignKey fkey : table.getForeignKeyCollection()) { - if (columns.isEmpty()) break; - fkey.getColumns().forEach(columns::remove); - } - - return columns.isEmpty(); - - } else { - return false; - } - } - - protected RevengStrategy getRoot() { - return settings.getRootStrategy(); - } - - public String foreignKeyToManyToManyName(ForeignKey fromKey, TableIdentifier middleTable, ForeignKey toKey, boolean uniqueReference) { - String propertyName = Introspector.decapitalize( StringHelper.unqualify( getRoot().tableToClassName(TableIdentifier.create( toKey.getReferencedTable()) )) ); - propertyName = pluralize( propertyName ); - - if(!uniqueReference) { - //TODO: maybe use the middleTable name here ? - if(toKey.getColumns()!=null && toKey.getColumns().size()==1) { - String columnName = ( (Column) toKey.getColumns().get(0) ).getName(); - propertyName = propertyName + "For" + toUpperCamelCase(columnName); - } - else { // composite key or no columns at all safeguard - propertyName = propertyName + "For" + toUpperCamelCase(toKey.getName()); - } + + for (ForeignKey fkey : table.getForeignKeyCollection()) { + if (columns.isEmpty()) break; + fkey.getColumns().forEach(columns::remove); + } + + return columns.isEmpty(); + } - return propertyName; - } + else { + return false; + } + } - public Map tableToMetaAttributes(TableIdentifier tableIdentifier) { - return null; - } + protected RevengStrategy getRoot() { + return settings.getRootStrategy(); + } - public Map columnToMetaAttributes(TableIdentifier identifier, String column) { - return null; - } + public String foreignKeyToManyToManyName(ForeignKey fromKey, TableIdentifier middleTable, ForeignKey toKey, boolean uniqueReference) { + String propertyName = Introspector.decapitalize( StringHelper.unqualify( getRoot().tableToClassName(TableIdentifier.create( toKey.getReferencedTable()) )) ); + propertyName = pluralize( propertyName ); + + if(!uniqueReference) { + //TODO: maybe use the middleTable name here ? + if(toKey.getColumns()!=null && toKey.getColumns().size()==1) { + String columnName = toKey.getColumns().get(0).getName(); + propertyName = propertyName + "For" + toUpperCamelCase(columnName); + } + else { // composite key or no columns at all safeguard + propertyName = propertyName + "For" + toUpperCamelCase(toKey.getName()); + } + } + return propertyName; + } + + public Map tableToMetaAttributes(TableIdentifier tableIdentifier) { + return null; + } + + public Map columnToMetaAttributes(TableIdentifier identifier, String column) { + return null; + } + + public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) { + return null; + } + + public AssociationInfo foreignKeyToInverseAssociationInfo(ForeignKey foreignKey) { + return null; + } - public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) { - return null; - } - public AssociationInfo foreignKeyToInverseAssociationInfo(ForeignKey foreignKey) { - return null; - } - - } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideBinder.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideBinder.java index 2c2c6a8ff0..680d48ad86 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideBinder.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideBinder.java @@ -41,439 +41,445 @@ public class OverrideBinder { - public static void bindRoot(OverrideRepository repository, Document doc) { - Element rootElement = doc.getDocumentElement(); - bindSchemaSelections(getChildElements(rootElement, "schema-selection"), repository); - bindTypeMappings(getChildElements(rootElement, "type-mapping"), repository); - bindTableFilters(getChildElements(rootElement, "table-filter"), repository); - bindTables(getChildElements(rootElement, "table"), repository); - } + public static void bindRoot(OverrideRepository repository, Document doc) { + Element rootElement = doc.getDocumentElement(); + bindSchemaSelections(getChildElements(rootElement, "schema-selection"), repository); + bindTypeMappings(getChildElements(rootElement, "type-mapping"), repository); + bindTableFilters(getChildElements(rootElement, "table-filter"), repository); + bindTables(getChildElements(rootElement, "table"), repository); + } - private static void bindSchemaSelections( - ArrayList schemaSelections, - OverrideRepository repository) { - for (Element schemaSelection : schemaSelections) { - bindSchemaSelection(schemaSelection, repository); - } - } + private static void bindSchemaSelections( + ArrayList schemaSelections, + OverrideRepository repository) { + for (Element schemaSelection : schemaSelections) { + bindSchemaSelection(schemaSelection, repository); + } + } - private static void bindTypeMappings( - ArrayList typeMappings, - OverrideRepository repository) { - if ( !typeMappings.isEmpty() ) { - bindTypeMapping(typeMappings.get(0), repository); - } - } + private static void bindTypeMappings( + ArrayList typeMappings, + OverrideRepository repository) { + if ( !typeMappings.isEmpty() ) { + bindTypeMapping(typeMappings.get(0), repository); + } + } - private static void bindTableFilters( - ArrayList tableFilters, - OverrideRepository repository) { - for (Element element : tableFilters) { - TableFilter tableFilter = new TableFilter(); - tableFilter.setMatchCatalog(getAttribute(element, "match-catalog")); - tableFilter.setMatchSchema(getAttribute(element, "match-schema")); - tableFilter.setMatchName(getAttribute(element, "match-name")); - tableFilter.setExclude(Boolean.valueOf(getAttribute(element, "exclude"))); - tableFilter.setPackage(getAttribute(element, "package")); - MultiValuedMap map = - MetaAttributeHelper.loadAndMergeMetaMap( - element, - new HashSetValuedHashMap()); - if ( !map.isEmpty() ) { - tableFilter.setMetaAttributes(map); - } else { - tableFilter.setMetaAttributes(null); - } - repository.addTableFilter(tableFilter); - } - } + private static void bindTableFilters( + ArrayList tableFilters, + OverrideRepository repository) { + for (Element element : tableFilters) { + TableFilter tableFilter = new TableFilter(); + tableFilter.setMatchCatalog(getAttribute(element, "match-catalog")); + tableFilter.setMatchSchema(getAttribute(element, "match-schema")); + tableFilter.setMatchName(getAttribute(element, "match-name")); + tableFilter.setExclude(Boolean.valueOf(getAttribute(element, "exclude"))); + tableFilter.setPackage(getAttribute(element, "package")); + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap<>()); + if ( !map.isEmpty() ) { + tableFilter.setMetaAttributes(map); + } + else { + tableFilter.setMetaAttributes(null); + } + repository.addTableFilter(tableFilter); + } + } - private static void bindTables( - ArrayList tables, - OverrideRepository repository) { - for (Element element : tables) { - Table table = new Table("Hibernate Tools"); - table.setCatalog(getAttribute(element, "catalog")); - table.setSchema(getAttribute(element, "schema")); - table.setName(getAttribute(element, "name")); - ArrayList primaryKeys = getChildElements(element, "primary-key"); - if ( !primaryKeys.isEmpty() ) { - bindPrimaryKey(primaryKeys.get(0), table, repository); - } - bindColumns(getChildElements(element, "column"), table, repository); - bindForeignKeys(getChildElements(element, "foreign-key"), table, repository); - bindMetaAttributes(element, table, repository); - repository.addTable(table, getAttribute(element, "class")); - } - } + private static void bindTables( + ArrayList tables, + OverrideRepository repository) { + for (Element element : tables) { + Table table = new Table("Hibernate Tools"); + table.setCatalog(getAttribute(element, "catalog")); + table.setSchema(getAttribute(element, "schema")); + table.setName(getAttribute(element, "name")); + ArrayList primaryKeys = getChildElements(element, "primary-key"); + if ( !primaryKeys.isEmpty() ) { + bindPrimaryKey(primaryKeys.get(0), table, repository); + } + bindColumns(getChildElements(element, "column"), table, repository); + bindForeignKeys(getChildElements(element, "foreign-key"), table, repository); + bindMetaAttributes(element, table, repository); + repository.addTable(table, getAttribute(element, "class")); + } + } - private static void bindPrimaryKey( - Element element, - Table table, - OverrideRepository repository) { - String propertyName = getAttribute(element, "property"); - String compositeIdName = getAttribute(element, "id-class"); - ArrayList generators = getChildElements(element, "generator"); - if ( !generators.isEmpty() ) { - Element generator = generators.get(0); - String identifierClass = getAttribute(generator, "class"); - Properties params = new Properties(); - ArrayList parameterList = getChildElements(generator, "param"); - for ( Element parameter : parameterList ) { - params.setProperty( getAttribute( parameter, "name" ), parameter.getTextContent() ); - } - repository.addTableIdentifierStrategy(table, identifierClass, params); - } - List boundColumnNames = bindColumns(getChildElements(element, "key-column"), table, repository); - repository.addPrimaryKeyNamesForTable(table, boundColumnNames, propertyName, compositeIdName); - } + private static void bindPrimaryKey( + Element element, + Table table, + OverrideRepository repository) { + String propertyName = getAttribute(element, "property"); + String compositeIdName = getAttribute(element, "id-class"); + ArrayList generators = getChildElements(element, "generator"); + if ( !generators.isEmpty() ) { + Element generator = generators.get(0); + String identifierClass = getAttribute(generator, "class"); + Properties params = new Properties(); + ArrayList parameterList = getChildElements(generator, "param"); + for ( Element parameter : parameterList ) { + params.setProperty( getAttribute( parameter, "name" ), parameter.getTextContent() ); + } + repository.addTableIdentifierStrategy(table, identifierClass, params); + } + List boundColumnNames = bindColumns(getChildElements(element, "key-column"), table, repository); + repository.addPrimaryKeyNamesForTable(table, boundColumnNames, propertyName, compositeIdName); + } - private static List bindColumns( - ArrayList columns, - Table table, - OverrideRepository repository) { - List columnNames = new ArrayList(); - for (Element element : columns) { - Column column = new Column(); - column.setName(getAttribute(element, "name")); - String attributeValue = getAttribute(element, "jdbc-type"); - if (StringHelper.isNotEmpty(attributeValue)) { - column.setSqlTypeCode( JdbcToHibernateTypeHelper.getJDBCType( attributeValue ) ); - } - TableIdentifier tableIdentifier = TableIdentifier.create(table); - if (table.getColumn(column) != null) { - throw new MappingException("Column " + column.getName() + " already exists in table " + tableIdentifier ); - } - MultiValuedMap map = - MetaAttributeHelper.loadAndMergeMetaMap( - element, - new HashSetValuedHashMap()); - if( !map.isEmpty() ) { - repository.addMetaAttributeInfo( tableIdentifier, column.getName(), map); - } - table.addColumn(column); - columnNames.add(column.getName()); - repository.setTypeNameForColumn( - tableIdentifier, - column.getName(), - getAttribute(element, "type")); - repository.setPropertyNameForColumn( - tableIdentifier, - column.getName(), - getAttribute(element, "property")); - boolean excluded = Boolean.parseBoolean(element.getAttribute("exclude") ); - if(excluded) { - repository.setExcludedColumn(tableIdentifier, column.getName()); - } - if (element.hasAttribute("foreign-table")) { - String foreignTableName = element.getAttribute("foreign-table"); - List localColumns = new ArrayList(); - localColumns.add(column); - List foreignColumns = new ArrayList(); - Table foreignTable = new Table("Hibernate Tools"); - foreignTable.setName(foreignTableName); - foreignTable.setCatalog( - element.hasAttribute("foreign-catalog") ? - element.getAttribute("foreign-catalog") : - table.getCatalog()); - foreignTable.setSchema( - element.hasAttribute("foreign-schema") ? - element.getAttribute("foreign-schema") : - table.getSchema()); - if (element.hasAttribute("foreign-column")) { - String foreignColumnName = element.getAttribute("foreign-column"); - Column foreignColumn = new Column(); - foreignColumn.setName(foreignColumnName); - foreignColumns.add(foreignColumn); - } else { - throw new MappingException("foreign-column is required when foreign-table is specified on " + column); - } - ForeignKey key = table.createForeignKey( - null, - localColumns, - foreignTableName, - null, - null, - foreignColumns); - key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) - } - } - return columnNames; - } + private static List bindColumns( + ArrayList columns, + Table table, + OverrideRepository repository) { + List columnNames = new ArrayList<>(); + for (Element element : columns) { + Column column = new Column(); + column.setName(getAttribute(element, "name")); + String attributeValue = getAttribute(element, "jdbc-type"); + if (StringHelper.isNotEmpty(attributeValue)) { + column.setSqlTypeCode( JdbcToHibernateTypeHelper.getJDBCType( attributeValue ) ); + } + TableIdentifier tableIdentifier = TableIdentifier.create(table); + if (table.getColumn(column) != null) { + throw new MappingException("Column " + column.getName() + " already exists in table " + tableIdentifier ); + } + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap<>()); + if( !map.isEmpty() ) { + repository.addMetaAttributeInfo( tableIdentifier, column.getName(), map); + } + table.addColumn(column); + columnNames.add(column.getName()); + repository.setTypeNameForColumn( + tableIdentifier, + column.getName(), + getAttribute(element, "type")); + repository.setPropertyNameForColumn( + tableIdentifier, + column.getName(), + getAttribute(element, "property")); + boolean excluded = Boolean.parseBoolean(element.getAttribute("exclude") ); + if(excluded) { + repository.setExcludedColumn(tableIdentifier, column.getName()); + } + if (element.hasAttribute("foreign-table")) { + String foreignTableName = element.getAttribute("foreign-table"); + List localColumns = new ArrayList<>(); + localColumns.add(column); + List foreignColumns = new ArrayList<>(); + Table foreignTable = new Table("Hibernate Tools"); + foreignTable.setName(foreignTableName); + foreignTable.setCatalog( + element.hasAttribute("foreign-catalog") ? + element.getAttribute("foreign-catalog") : + table.getCatalog()); + foreignTable.setSchema( + element.hasAttribute("foreign-schema") ? + element.getAttribute("foreign-schema") : + table.getSchema()); + if (element.hasAttribute("foreign-column")) { + String foreignColumnName = element.getAttribute("foreign-column"); + Column foreignColumn = new Column(); + foreignColumn.setName(foreignColumnName); + foreignColumns.add(foreignColumn); + } + else { + throw new MappingException("foreign-column is required when foreign-table is specified on " + column); + } + ForeignKey key = table.createForeignKey( + null, + localColumns, + foreignTableName, + null, + null, + foreignColumns); + key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) + } + } + return columnNames; + } - private static void bindForeignKeys( - ArrayList foreignKeys, - Table table, - OverrideRepository repository) { - for (Element element : foreignKeys) { - String constraintName = getAttribute(element, "constraint-name"); - String foreignTableName = getAttribute(element, "foreign-table"); - if (foreignTableName != null) { - Table foreignTable = new Table("hibernate tools"); - foreignTable.setName(foreignTableName); - foreignTable.setCatalog( - element.hasAttribute("foreign-catalog") ? - element.getAttribute("foreign-catalog") : - table.getCatalog()); - foreignTable.setSchema( - element.hasAttribute("foreign-schema") ? - element.getAttribute("foreign-schema") : - table.getSchema()); - List localColumns = new ArrayList(); - List foreignColumns = new ArrayList(); - ArrayList columnRefs = getChildElements(element, "column-ref"); - for (Element columnRef : columnRefs) { - localColumns.add(new Column(columnRef.getAttribute("local-column"))); - foreignColumns.add(new Column(columnRef.getAttribute("foreign-column"))); - } - ForeignKey key = table.createForeignKey( - constraintName, - localColumns, - foreignTableName, - null, - null, - foreignColumns); - key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) - } - if (StringHelper.isNotEmpty(constraintName)) { - if (!validateFkAssociations(element)) { - throw new IllegalArgumentException("you can't mix or with <(inverse-)one-to-one/> "); - } - if (!bindManyToOneAndCollection(element, constraintName, repository)) { - bindOneToOne(element, constraintName, repository); - } - } + private static void bindForeignKeys( + ArrayList foreignKeys, + Table table, + OverrideRepository repository) { + for (Element element : foreignKeys) { + String constraintName = getAttribute(element, "constraint-name"); + String foreignTableName = getAttribute(element, "foreign-table"); + if (foreignTableName != null) { + Table foreignTable = new Table("hibernate tools"); + foreignTable.setName(foreignTableName); + foreignTable.setCatalog( + element.hasAttribute("foreign-catalog") ? + element.getAttribute("foreign-catalog") : + table.getCatalog()); + foreignTable.setSchema( + element.hasAttribute("foreign-schema") ? + element.getAttribute("foreign-schema") : + table.getSchema()); + List localColumns = new ArrayList<>(); + List foreignColumns = new ArrayList<>(); + ArrayList columnRefs = getChildElements(element, "column-ref"); + for (Element columnRef : columnRefs) { + localColumns.add(new Column(columnRef.getAttribute("local-column"))); + foreignColumns.add(new Column(columnRef.getAttribute("foreign-column"))); + } + ForeignKey key = table.createForeignKey( + constraintName, + localColumns, + foreignTableName, + null, + null, + foreignColumns); + key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) + } + if (StringHelper.isNotEmpty(constraintName)) { + if (!validateFkAssociations(element)) { + throw new IllegalArgumentException("you can't mix or with <(inverse-)one-to-one/> "); + } + if (!bindManyToOneAndCollection(element, constraintName, repository)) { + bindOneToOne(element, constraintName, repository); + } + } - } - } + } + } - private static void bindOneToOne(Element element, String constraintName, - OverrideRepository repository) { - String oneToOneProperty = null; - Boolean excludeOneToOne = null; - ArrayList oneToOnes = getChildElements(element, "one-to-one"); - Element oneToOne = null; - AssociationInfo associationInfo = null; - if( !oneToOnes.isEmpty() ) { - oneToOne = oneToOnes.get(0); - oneToOneProperty = getAttribute(oneToOne, "property"); - excludeOneToOne = Boolean.valueOf(oneToOne.getAttribute("exclude")); - associationInfo = extractAssociationInfo(oneToOne); - } + private static void bindOneToOne(Element element, String constraintName, + OverrideRepository repository) { + String oneToOneProperty = null; + Boolean excludeOneToOne = null; + ArrayList oneToOnes = getChildElements(element, "one-to-one"); + Element oneToOne = null; + AssociationInfo associationInfo = null; + if( !oneToOnes.isEmpty() ) { + oneToOne = oneToOnes.get(0); + oneToOneProperty = getAttribute(oneToOne, "property"); + excludeOneToOne = Boolean.valueOf(oneToOne.getAttribute("exclude")); + associationInfo = extractAssociationInfo(oneToOne); + } - String inverseOneToOneProperty = null; - Boolean excludeInverseOneToOne = null; - ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); - Element inverseOneToOne = null; - AssociationInfo inverseAssociationInfo = null; - if( !inverseOneToOnes.isEmpty() ) { - inverseOneToOne = inverseOneToOnes.get(0); - inverseOneToOneProperty = getAttribute(inverseOneToOne, "property"); - excludeInverseOneToOne = Boolean.valueOf(inverseOneToOne.getAttribute("exclude")); - inverseAssociationInfo = extractAssociationInfo(inverseOneToOne); - } - // having oneToOne = null and inverseOneToOne != null doesn't make sense - // we cannot have the inverse side without the owning side in this case - if ( (oneToOne!=null) ) { - repository.addForeignKeyInfo( - constraintName, - oneToOneProperty, - excludeOneToOne, - inverseOneToOneProperty, - excludeInverseOneToOne, - associationInfo, - inverseAssociationInfo); - } - } + String inverseOneToOneProperty = null; + Boolean excludeInverseOneToOne = null; + ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); + Element inverseOneToOne; + AssociationInfo inverseAssociationInfo = null; + if( !inverseOneToOnes.isEmpty() ) { + inverseOneToOne = inverseOneToOnes.get(0); + inverseOneToOneProperty = getAttribute(inverseOneToOne, "property"); + excludeInverseOneToOne = Boolean.valueOf(inverseOneToOne.getAttribute("exclude")); + inverseAssociationInfo = extractAssociationInfo(inverseOneToOne); + } + // having oneToOne = null and inverseOneToOne != null doesn't make sense + // we cannot have the inverse side without the owning side in this case + if ( (oneToOne!=null) ) { + repository.addForeignKeyInfo( + constraintName, + oneToOneProperty, + excludeOneToOne, + inverseOneToOneProperty, + excludeInverseOneToOne, + associationInfo, + inverseAssociationInfo); + } + } - private static boolean bindManyToOneAndCollection( - Element element, - String constraintName, - OverrideRepository repository) { - String manyToOneProperty = null; - Boolean excludeManyToOne = null; - AssociationInfo associationInfo = null; - AssociationInfo inverseAssociationInfo = null; - ArrayList manyToOnes = getChildElements(element, "many-to-one"); - Element manyToOne = null; - if ( !manyToOnes.isEmpty() ) { - manyToOne = manyToOnes.get(0); - manyToOneProperty = getAttribute(manyToOne, "property"); - excludeManyToOne = Boolean.valueOf(manyToOne.getAttribute("exclude")); - associationInfo = extractAssociationInfo(manyToOne); - } - String collectionProperty = null; - Boolean excludeCollection = null; - ArrayList sets = getChildElements(element, "set"); - Element set = null; - if ( !sets.isEmpty() ) { - set = sets.get(0); - collectionProperty = getAttribute(set, "property"); - excludeCollection = Boolean.valueOf(set.getAttribute("exclude")); - inverseAssociationInfo = extractAssociationInfo(set); - } - if ( (manyToOne!=null) || (set!=null) ) { - repository.addForeignKeyInfo( - constraintName, - manyToOneProperty, - excludeManyToOne, - collectionProperty, - excludeCollection, - associationInfo, - inverseAssociationInfo); - return true; - } else { - return false; - } - } + private static boolean bindManyToOneAndCollection( + Element element, + String constraintName, + OverrideRepository repository) { + String manyToOneProperty = null; + Boolean excludeManyToOne = null; + AssociationInfo associationInfo = null; + AssociationInfo inverseAssociationInfo = null; + ArrayList manyToOnes = getChildElements(element, "many-to-one"); + Element manyToOne = null; + if ( !manyToOnes.isEmpty() ) { + manyToOne = manyToOnes.get(0); + manyToOneProperty = getAttribute(manyToOne, "property"); + excludeManyToOne = Boolean.valueOf(manyToOne.getAttribute("exclude")); + associationInfo = extractAssociationInfo(manyToOne); + } + String collectionProperty = null; + Boolean excludeCollection = null; + ArrayList sets = getChildElements(element, "set"); + Element set = null; + if ( !sets.isEmpty() ) { + set = sets.get(0); + collectionProperty = getAttribute(set, "property"); + excludeCollection = Boolean.valueOf(set.getAttribute("exclude")); + inverseAssociationInfo = extractAssociationInfo(set); + } + if ( (manyToOne!=null) || (set!=null) ) { + repository.addForeignKeyInfo( + constraintName, + manyToOneProperty, + excludeManyToOne, + collectionProperty, + excludeCollection, + associationInfo, + inverseAssociationInfo); + return true; + } + else { + return false; + } + } - private static AssociationInfo extractAssociationInfo(Element manyToOne) { - return RevengUtils.createAssociationInfo( - manyToOne.hasAttribute("cascade") ? manyToOne.getAttribute("cascade") : null, - manyToOne.hasAttribute("fetch") ? manyToOne.getAttribute("fetch") : null, - manyToOne.hasAttribute("insert") ? - Boolean.parseBoolean(manyToOne.getAttribute("insert")) : null, - manyToOne.hasAttribute("update") ? - Boolean.parseBoolean(manyToOne.getAttribute("update")) : null); - } + private static AssociationInfo extractAssociationInfo(Element manyToOne) { + return RevengUtils.createAssociationInfo( + manyToOne.hasAttribute("cascade") ? manyToOne.getAttribute("cascade") : null, + manyToOne.hasAttribute("fetch") ? manyToOne.getAttribute("fetch") : null, + manyToOne.hasAttribute("insert") ? + Boolean.parseBoolean(manyToOne.getAttribute("insert")) : null, + manyToOne.hasAttribute("update") ? + Boolean.parseBoolean(manyToOne.getAttribute("update")) : null); + } - private static boolean validateFkAssociations(Element element){ - ArrayList manyToOnes = getChildElements(element, "many-to-one"); - ArrayList oneToOnes = getChildElements(element, "one-to-one"); - ArrayList sets = getChildElements(element, "set"); - ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); - if ( !manyToOnes.isEmpty() && - (!oneToOnes.isEmpty() || !inverseOneToOnes.isEmpty())) { - return false; - } - if ( !oneToOnes.isEmpty() && !sets.isEmpty() ) { - return false; - } - return inverseOneToOnes.isEmpty() || sets.isEmpty(); - } + private static boolean validateFkAssociations(Element element){ + ArrayList manyToOnes = getChildElements(element, "many-to-one"); + ArrayList oneToOnes = getChildElements(element, "one-to-one"); + ArrayList sets = getChildElements(element, "set"); + ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); + if ( !manyToOnes.isEmpty() && + (!oneToOnes.isEmpty() || !inverseOneToOnes.isEmpty())) { + return false; + } + if ( !oneToOnes.isEmpty() && !sets.isEmpty() ) { + return false; + } + return inverseOneToOnes.isEmpty() || sets.isEmpty(); + } - private static void bindMetaAttributes( - Element element, - Table table, - OverrideRepository repository) { - MultiValuedMap map = - MetaAttributeHelper.loadAndMergeMetaMap( - element, - new HashSetValuedHashMap()); - if( !map.isEmpty() ) { - repository.addMetaAttributeInfo( table, map); - } - } + private static void bindMetaAttributes( + Element element, + Table table, + OverrideRepository repository) { + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap<>()); + if( !map.isEmpty() ) { + repository.addMetaAttributeInfo( table, map); + } + } - private static void bindSchemaSelection( - Element schemaSelectionElement, - OverrideRepository repository) { - repository.addSchemaSelection( - new SchemaSelection() { - @Override - public String getMatchCatalog() { - return getAttribute(schemaSelectionElement, "match-catalog"); - } - @Override - public String getMatchSchema() { - return getAttribute(schemaSelectionElement, "match-schema"); - } - @Override - public String getMatchTable() { - return getAttribute(schemaSelectionElement, "match-table"); - } + private static void bindSchemaSelection( + Element schemaSelectionElement, + OverrideRepository repository) { + repository.addSchemaSelection( + new SchemaSelection() { + @Override + public String getMatchCatalog() { + return getAttribute(schemaSelectionElement, "match-catalog"); + } + @Override + public String getMatchSchema() { + return getAttribute(schemaSelectionElement, "match-schema"); + } + @Override + public String getMatchTable() { + return getAttribute(schemaSelectionElement, "match-table"); + } - }); - } + }); + } - private static void bindTypeMapping( - Element typeMapping, - OverrideRepository repository) { - ArrayList sqlTypes = getChildElements(typeMapping, "sql-type"); - for ( Element sqlType : sqlTypes ) { - bindSqlType( sqlType, repository ); - } - } + private static void bindTypeMapping( + Element typeMapping, + OverrideRepository repository) { + ArrayList sqlTypes = getChildElements(typeMapping, "sql-type"); + for ( Element sqlType : sqlTypes ) { + bindSqlType( sqlType, repository ); + } + } - private static void bindSqlType(Element sqlType, OverrideRepository repository) { - int jdbcType = JdbcToHibernateTypeHelper.getJDBCType( - getAttribute(sqlType, "jdbc-type")); - SQLTypeMapping sqlTypeMapping = new SQLTypeMapping(jdbcType); - sqlTypeMapping.setHibernateType(getHibernateType(sqlType)); - sqlTypeMapping.setLength(getInteger( - getAttribute(sqlType, "length"), - SQLTypeMapping.UNKNOWN_LENGTH)); - sqlTypeMapping.setPrecision(getInteger( - getAttribute(sqlType, "precision"), - SQLTypeMapping.UNKNOWN_PRECISION)); - sqlTypeMapping.setScale(getInteger( - getAttribute(sqlType, "scale"), - SQLTypeMapping.UNKNOWN_SCALE)); - String notNull = getAttribute(sqlType, "not-null"); - if (StringHelper.isEmpty(notNull)) { - sqlTypeMapping.setNullable(null); - } else { - sqlTypeMapping.setNullable(notNull.equals("false")); - } - if (StringHelper.isEmpty(sqlTypeMapping.getHibernateType())) { - throw new MappingException( - "No hibernate-type specified for " + - sqlType.getAttribute("jdbc-type") + - " at " + - sqlType.getTagName()); - } - repository.addTypeMapping(sqlTypeMapping); - } + private static void bindSqlType(Element sqlType, OverrideRepository repository) { + int jdbcType = JdbcToHibernateTypeHelper.getJDBCType( + getAttribute(sqlType, "jdbc-type")); + SQLTypeMapping sqlTypeMapping = new SQLTypeMapping(jdbcType); + sqlTypeMapping.setHibernateType(getHibernateType(sqlType)); + sqlTypeMapping.setLength(getInteger( + getAttribute(sqlType, "length"), + SQLTypeMapping.UNKNOWN_LENGTH)); + sqlTypeMapping.setPrecision(getInteger( + getAttribute(sqlType, "precision"), + SQLTypeMapping.UNKNOWN_PRECISION)); + sqlTypeMapping.setScale(getInteger( + getAttribute(sqlType, "scale"), + SQLTypeMapping.UNKNOWN_SCALE)); + String notNull = getAttribute(sqlType, "not-null"); + if (StringHelper.isEmpty(notNull)) { + sqlTypeMapping.setNullable(null); + } + else { + sqlTypeMapping.setNullable(notNull.equals("false")); + } + if (StringHelper.isEmpty(sqlTypeMapping.getHibernateType())) { + throw new MappingException( + "No hibernate-type specified for " + + sqlType.getAttribute("jdbc-type") + + " at " + + sqlType.getTagName()); + } + repository.addTypeMapping(sqlTypeMapping); + } - private static String getHibernateType(Element element) { - String attributeValue = getAttribute(element, "hibernate-type"); - if(StringHelper.isEmpty(attributeValue)) { - ArrayList hibernateTypes = getChildElements(element, "hibernate-type"); - if ( !hibernateTypes.isEmpty() ) { - Element hibernateType = hibernateTypes.get(0); - if (hibernateType.hasAttribute("name")) { - return hibernateType.getAttribute("name"); - } - } else { - return null; - } - } - return attributeValue; - } + private static String getHibernateType(Element element) { + String attributeValue = getAttribute(element, "hibernate-type"); + if(StringHelper.isEmpty(attributeValue)) { + ArrayList hibernateTypes = getChildElements(element, "hibernate-type"); + if ( !hibernateTypes.isEmpty() ) { + Element hibernateType = hibernateTypes.get(0); + if (hibernateType.hasAttribute("name")) { + return hibernateType.getAttribute("name"); + } + } + else { + return null; + } + } + return attributeValue; + } - private static int getInteger(String string, int defaultValue) { - if(string==null) { - return defaultValue; - } - else { - try { - return Integer.parseInt(string); - } catch (NumberFormatException e) { - throw new RuntimeException(e); - } - } - } + private static int getInteger(String string, int defaultValue) { + if(string==null) { + return defaultValue; + } + else { + try { + return Integer.parseInt(string); + } + catch (NumberFormatException e) { + throw new RuntimeException(e); + } + } + } - private static ArrayList getChildElements(Element parent, String tagName) { - ArrayList result = new ArrayList(); - NodeList nodeList = parent.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node instanceof Element) { - if (tagName.equals(((Element)node).getTagName())) { - result.add((Element)node); - } - } - } - return result; - } + private static ArrayList getChildElements(Element parent, String tagName) { + ArrayList result = new ArrayList<>(); + NodeList nodeList = parent.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element) { + if (tagName.equals(((Element)node).getTagName())) { + result.add((Element)node); + } + } + } + return result; + } - private static String getAttribute(Element element, String attributeName) { - String result = null; - if (element.hasAttribute(attributeName)) { - result = element.getAttribute(attributeName); - } - return result; - } + private static String getAttribute(Element element, String attributeName) { + String result = null; + if (element.hasAttribute(attributeName)) { + result = element.getAttribute(attributeName); + } + return result; + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideRepository.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideRepository.java index a1b7356fec..7a9be43f62 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideRepository.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/OverrideRepository.java @@ -21,15 +21,7 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; +import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -51,515 +43,516 @@ import org.jboss.logging.Logger; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; -import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class OverrideRepository { - final private static Logger log = Logger.getLogger( OverrideRepository.class ); + final private static Logger log = Logger.getLogger( OverrideRepository.class ); - final private Map> typeMappings; // from sqltypes to list of SQLTypeMapping + final private Map> typeMappings; // from sqltypes to list of SQLTypeMapping - final private List tableFilters; + final private List tableFilters; - final private Map> foreignKeys; // key: TableIdentifier element: List of foreignkeys that references the Table + final private Map> foreignKeys; // key: TableIdentifier element: List of foreignkeys that references the Table - final private Map typeForColumn; + final private Map typeForColumn; - final private Map propertyNameForColumn; - - final private Map identifierStrategyForTable; - - final private Map identifierPropertiesForTable; - - final private Map> primaryKeyColumnsForTable; - - final private Set excludedColumns; - - final private TableToClassName tableToClassName; - - final private List schemaSelections; - - final private Map propertyNameForPrimaryKey; - - final private Map compositeIdNameForTable; - - final private Map foreignKeyToOneName; - - final private Map foreignKeyToInverseName; - - final private Map foreignKeyInverseExclude; - - final private Map foreignKeyToOneExclude; - - final private Map foreignKeyToEntityInfo; - final private Map foreignKeyToInverseEntityInfo; - - final private Map> tableMetaAttributes; // TI -> MultiMap of SimpleMetaAttributes - - final private Map> columnMetaAttributes; - - //private String defaultCatalog; - //private String defaultSchema; - - public OverrideRepository() { - //this.defaultCatalog = null; - //this.defaultSchema = null; - typeMappings = new HashMap>(); - tableFilters = new ArrayList(); - foreignKeys = new HashMap>(); - typeForColumn = new HashMap(); - propertyNameForColumn = new HashMap(); - identifierStrategyForTable = new HashMap(); - identifierPropertiesForTable = new HashMap(); - primaryKeyColumnsForTable = new HashMap>(); - propertyNameForPrimaryKey = new HashMap(); - tableToClassName = new TableToClassName(); - excludedColumns = new HashSet(); - schemaSelections = new ArrayList(); - compositeIdNameForTable = new HashMap(); - foreignKeyToOneName = new HashMap(); - foreignKeyToInverseName = new HashMap(); - foreignKeyInverseExclude = new HashMap(); - foreignKeyToOneExclude = new HashMap(); - tableMetaAttributes = new HashMap>(); - columnMetaAttributes = new HashMap>(); - foreignKeyToEntityInfo = new HashMap(); - foreignKeyToInverseEntityInfo = new HashMap(); - } - - public void addFile(File xmlFile) { - log.info( "Override file: " + xmlFile.getPath() ); - try { - addInputStream( xmlFile ); - } - catch ( Exception e ) { - log.error( "Could not configure overrides from file: " + xmlFile.getPath(), e ); - throw new MappingException( "Could not configure overrides from file: " + xmlFile.getPath(), e ); - } - } - - /** - * Read override from an application resource trying different classloaders. - * This method will try to load the resource first from the thread context - * classloader and then from the classloader that loaded Hibernate. - */ - public OverrideRepository addResource(String path) throws MappingException { - log.info( "Mapping resource: " + path ); - InputStream rsrc = Thread.currentThread().getContextClassLoader().getResourceAsStream( path ); - if ( rsrc == null ) rsrc = OverrideRepository.class.getClassLoader().getResourceAsStream( path ); - if ( rsrc == null ) throw new MappingException( "Resource: " + path + " not found" ); - try { - return addInputStream( rsrc ); - } - catch ( MappingException me ) { - throw new MappingException( "Error reading resource: " + path, me ); - } - } - - public OverrideRepository addInputStream(InputStream xmlInputStream) throws MappingException { - try { - final List errors = new ArrayList(); - ErrorHandler errorHandler = new ErrorHandler() { - @Override - public void warning(SAXParseException exception) throws SAXException { - log.warn("warning while parsing xml", exception); - } - @Override - public void error(SAXParseException exception) throws SAXException { - errors.add(exception); - } - @Override - public void fatalError(SAXParseException exception) throws SAXException { - error(exception); - } - }; - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - db.setErrorHandler(errorHandler); - Document document = db.parse(xmlInputStream); - if ( !errors.isEmpty()) throw new MappingException( "invalid override definition", ( Throwable ) errors.get( 0 ) ); - add( document ); - return this; - } - catch ( MappingException me ) { - throw me; - } - catch ( Exception e ) { - log.error( "Could not configure overrides from input stream", e ); - throw new MappingException( e ); - } - } - - public void addInputStream(File file) throws MappingException { - InputStream xmlInputStream = null; - try { - xmlInputStream = new FileInputStream( file ); - addInputStream( xmlInputStream ); - } - catch ( Exception e ) { - log.error( "Could not configure overrides from input stream", e ); - throw new MappingException( e ); - } - finally { - try { - if (xmlInputStream != null) { - xmlInputStream.close(); - } - } - catch ( IOException ioe ) { - log.error( "could not close input stream", ioe ); - } - } - } - - private void add(Document doc) { - OverrideBinder.bindRoot(this, doc); - } - - private String getPreferredHibernateType(int sqlType, int length, int precision, int scale, boolean nullable) { - List l = typeMappings.get(new TypeMappingKey(sqlType,length) ); - - if(l == null) { // if no precise length match found, then try to find matching unknown length matches - l = typeMappings.get(new TypeMappingKey(sqlType,SQLTypeMapping.UNKNOWN_LENGTH) ); - } - return scanForMatch( sqlType, length, precision, scale, nullable, l ); - } - - private String scanForMatch(int sqlType, int length, int precision, int scale, boolean nullable, List l) { - if(l!=null) { - for ( SQLTypeMapping element : l ) { - if ( element.getJDBCType() != sqlType ) return null; - if ( element.match( sqlType, length, precision, scale, nullable ) ) { - return element.getHibernateType(); - } - } - } - return null; - } - - public void addTypeMapping(SQLTypeMapping sqltype) { - TypeMappingKey key = new TypeMappingKey(sqltype); - List list = typeMappings.computeIfAbsent( key, k -> new ArrayList<>() ); - list.add(sqltype); - } - - static class TypeMappingKey { - - int type; - int length; - - TypeMappingKey(SQLTypeMapping mpa) { - type = mpa.getJDBCType(); - length = mpa.getLength(); - } - - public TypeMappingKey(int sqlType, int length) { - this.type = sqlType; - this.length = length; - } - - public boolean equals(Object obj) { - if(obj==null) return false; - if(!(obj instanceof TypeMappingKey other)) return false; - - - return type==other.type && length==other.length; - } - - public int hashCode() { - return (type + length) % 17; - } - - public String toString() { - return this.getClass() + "(type:" + type + ", length:" + length + ")"; - } - } - - protected String getPackageName(TableIdentifier identifier) { - for ( TableFilter tf : tableFilters ) { - String value = tf.getPackage( identifier ); - if ( value != null ) { - return value; - } - } - return null; - } - - protected boolean excludeTable(TableIdentifier identifier) { - Iterator iterator = tableFilters.iterator(); - boolean hasInclude = false; - - while(iterator.hasNext() ) { - TableFilter tf = iterator.next(); - Boolean value = tf.exclude(identifier); - if(value!=null) { - return value; - } - if(!tf.getExclude() ) { - hasInclude = true; - } - } - - return hasInclude; - } - - public void addTableFilter(TableFilter filter) { - tableFilters.add(filter); - } - - public RevengStrategy getReverseEngineeringStrategy(RevengStrategy delegate) { - return new DelegatingStrategy(delegate) { - - public boolean excludeTable(TableIdentifier ti) { - return OverrideRepository.this.excludeTable(ti); - } - - public Map tableToMetaAttributes(TableIdentifier tableIdentifier) { - return OverrideRepository.this.tableToMetaAttributes(tableIdentifier); - } - - public Map columnToMetaAttributes(TableIdentifier tableIdentifier, String column) { - return OverrideRepository.this.columnToMetaAttributes(tableIdentifier, column); - } - - public boolean excludeColumn(TableIdentifier identifier, String columnName) { - return excludedColumns.contains(new TableColumnKey(identifier, columnName)); - } - - public String tableToCompositeIdName(TableIdentifier identifier) { - String result = compositeIdNameForTable.get(identifier); - if(result==null) { - return super.tableToCompositeIdName(identifier); - } else { - return result; - } - } - public List getSchemaSelections() { - if(schemaSelections.isEmpty()) { - return super.getSchemaSelections(); - } else { - return schemaSelections; - } - } - - public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { - String result = null; - String location = ""; - String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; - if(table!=null) { - location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName; - } else { - - location += " Column: " + columnName + info; - } - if(table!=null && columnName!=null) { - result = typeForColumn.get(new TableColumnKey(table, columnName)); - if(result!=null) { - log.debug("explicit column mapping found for [" + location + "] to [" + result + "]"); - return result; - } - } - - result = OverrideRepository.this.getPreferredHibernateType(sqlType, length, precision, scale, nullable); - if(result==null) { - return super.columnToHibernateTypeName(table, columnName, sqlType, length, precision, scale, nullable, generatedIdentifier); - } - else { - log.debug(" found for [" + location + info + "] to [" + result + "]"); - return result; - } - } - - public String tableToClassName(TableIdentifier tableIdentifier) { - String className = tableToClassName.get(tableIdentifier); - - if(className!=null) { - if( className.contains( "." ) ) { - return className; - } else { - String packageName = getPackageName(tableIdentifier); - if(packageName==null) { - return className; - } else { - return StringHelper.qualify(packageName, className); - } - } - } - - String packageName = getPackageName(tableIdentifier); - if(packageName==null) { - return super.tableToClassName(tableIdentifier); - } - else { - String string = super.tableToClassName(tableIdentifier); - if(string==null) return null; - return StringHelper.qualify(packageName, StringHelper.unqualify(string)); - } - } - - public List getForeignKeys(TableIdentifier referencedTable) { - List list = foreignKeys.get(referencedTable); - if(list==null) { - return super.getForeignKeys(referencedTable); - } else { - return list; - } - } - - public String columnToPropertyName(TableIdentifier table, String column) { - String result = propertyNameForColumn.get(new TableColumnKey(table, column)); - if(result==null) { - return super.columnToPropertyName(table, column); - } else { - return result; - } - } - - public String tableToIdentifierPropertyName(TableIdentifier tableIdentifier) { - String result = propertyNameForPrimaryKey.get(tableIdentifier); - if(result==null) { - return super.tableToIdentifierPropertyName(tableIdentifier); - } else { - return result; - } - } - - public String getTableIdentifierStrategyName(TableIdentifier tableIdentifier) { - String result = identifierStrategyForTable.get(tableIdentifier); - if(result==null) { - return super.getTableIdentifierStrategyName( tableIdentifier ); - } else { - log.debug("tableIdentifierStrategy for " + tableIdentifier + " -> '" + result + "'"); - return result; - } - } - - public Properties getTableIdentifierProperties(TableIdentifier tableIdentifier) { - Properties result = identifierPropertiesForTable.get(tableIdentifier); - if(result==null) { - return super.getTableIdentifierProperties( tableIdentifier ); - } else { - return result; - } - } - - public List getPrimaryKeyColumnNames(TableIdentifier tableIdentifier) { - List result = primaryKeyColumnsForTable.get(tableIdentifier); - if(result==null) { - return super.getPrimaryKeyColumnNames(tableIdentifier); - } else { - return result; - } - } - - public String foreignKeyToEntityName(String keyname, TableIdentifier fromTable, List fromColumnNames, TableIdentifier referencedTable, List referencedColumnNames, boolean uniqueReference) { - String property = foreignKeyToOneName.get(keyname); - if(property==null) { - return super.foreignKeyToEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); - } else { - return property; - } - } - - - public String foreignKeyToInverseEntityName(String keyname, - TableIdentifier fromTable, List fromColumnNames, - TableIdentifier referencedTable, - List referencedColumnNames, boolean uniqueReference) { - - String property = foreignKeyToInverseName.get(keyname); - if(property==null) { - return super.foreignKeyToInverseEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); - } else { - return property; - } - } - - public String foreignKeyToCollectionName(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns, boolean uniqueReference) { - String property = foreignKeyToInverseName.get(keyname); - if(property==null) { - return super.foreignKeyToCollectionName(keyname, fromTable, fromColumns, referencedTable, referencedColumns, uniqueReference); - } else { - return property; - } - } - - public boolean excludeForeignKeyAsCollection( - String keyname, - TableIdentifier fromTable, - List fromColumns, - TableIdentifier referencedTable, - List referencedColumns) { - Boolean bool = foreignKeyInverseExclude.get(keyname); - if(bool!=null) { - return bool; - } else { - return super.excludeForeignKeyAsCollection( keyname, fromTable, fromColumns, - referencedTable, referencedColumns ); - } - } - - public boolean excludeForeignKeyAsManytoOne( - String keyname, - TableIdentifier fromTable, - List fromColumns, TableIdentifier - referencedTable, - List referencedColumns) { - Boolean bool = (Boolean) foreignKeyToOneExclude.get(keyname); - if(bool!=null) { - return bool; - } else { - return super.excludeForeignKeyAsManytoOne( keyname, fromTable, fromColumns, - referencedTable, referencedColumns ); - } - } - - - public AssociationInfo foreignKeyToInverseAssociationInfo(ForeignKey foreignKey) { - AssociationInfo fkei = foreignKeyToInverseEntityInfo.get(foreignKey.getName()); - if(fkei!=null) { - return fkei; - } else { - return super.foreignKeyToInverseAssociationInfo(foreignKey); - } - } - - public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) { - AssociationInfo fkei = foreignKeyToEntityInfo.get(foreignKey.getName()); - if(fkei!=null) { - return fkei; - } else { - return super.foreignKeyToAssociationInfo(foreignKey); - } - } - }; - } - - protected Map columnToMetaAttributes(TableIdentifier tableIdentifier, String column) { - MultiValuedMap specific = columnMetaAttributes.get( new TableColumnKey(tableIdentifier, column) ); - if(specific!=null && !specific.isEmpty()) { - return toMetaAttributes(specific); - } - - return null; - } - - // TODO: optimize - protected Map tableToMetaAttributes(TableIdentifier identifier) { - MultiValuedMap specific = tableMetaAttributes.get( identifier ); - if(specific!=null && !specific.isEmpty()) { - return toMetaAttributes(specific); - } - MultiValuedMap general = findGeneralAttributes( identifier ); - if(general!=null && !general.isEmpty()) { - return toMetaAttributes(general); - } - - return null; + final private Map propertyNameForColumn; + + final private Map identifierStrategyForTable; + + final private Map identifierPropertiesForTable; + + final private Map> primaryKeyColumnsForTable; + + final private Set excludedColumns; + + final private TableToClassName tableToClassName; + + final private List schemaSelections; + + final private Map propertyNameForPrimaryKey; + + final private Map compositeIdNameForTable; + + final private Map foreignKeyToOneName; + + final private Map foreignKeyToInverseName; + + final private Map foreignKeyInverseExclude; + + final private Map foreignKeyToOneExclude; + + final private Map foreignKeyToEntityInfo; + final private Map foreignKeyToInverseEntityInfo; + + final private Map> tableMetaAttributes; // TI -> MultiMap of SimpleMetaAttributes + + final private Map> columnMetaAttributes; + + //private String defaultCatalog; + //private String defaultSchema; + + public OverrideRepository() { + //this.defaultCatalog = null; + //this.defaultSchema = null; + typeMappings = new HashMap<>(); + tableFilters = new ArrayList<>(); + foreignKeys = new HashMap<>(); + typeForColumn = new HashMap<>(); + propertyNameForColumn = new HashMap<>(); + identifierStrategyForTable = new HashMap<>(); + identifierPropertiesForTable = new HashMap<>(); + primaryKeyColumnsForTable = new HashMap<>(); + propertyNameForPrimaryKey = new HashMap<>(); + tableToClassName = new TableToClassName(); + excludedColumns = new HashSet<>(); + schemaSelections = new ArrayList<>(); + compositeIdNameForTable = new HashMap<>(); + foreignKeyToOneName = new HashMap<>(); + foreignKeyToInverseName = new HashMap<>(); + foreignKeyInverseExclude = new HashMap<>(); + foreignKeyToOneExclude = new HashMap<>(); + tableMetaAttributes = new HashMap<>(); + columnMetaAttributes = new HashMap<>(); + foreignKeyToEntityInfo = new HashMap<>(); + foreignKeyToInverseEntityInfo = new HashMap<>(); + } + + public void addFile(File xmlFile) { + log.info( "Override file: " + xmlFile.getPath() ); + try { + addInputStream( xmlFile ); + } + catch ( Exception e ) { + log.error( "Could not configure overrides from file: " + xmlFile.getPath(), e ); + throw new MappingException( "Could not configure overrides from file: " + xmlFile.getPath(), e ); + } + + } + + /** + * Read override from an application resource trying different classloaders. + * This method will try to load the resource first from the thread context + * classloader and then from the classloader that loaded Hibernate. + */ + public OverrideRepository addResource(String path) throws MappingException { + log.info( "Mapping resource: " + path ); + InputStream rsrc = Thread.currentThread().getContextClassLoader().getResourceAsStream( path ); + if ( rsrc == null ) rsrc = OverrideRepository.class.getClassLoader().getResourceAsStream( path ); + if ( rsrc == null ) throw new MappingException( "Resource: " + path + " not found" ); + try { + return addInputStream( rsrc ); + } + catch ( MappingException me ) { + throw new MappingException( "Error reading resource: " + path, me ); + } + } + + public OverrideRepository addInputStream(InputStream xmlInputStream) throws MappingException { + try { + final List errors = new ArrayList<>(); + ErrorHandler errorHandler = new ErrorHandler() { + @Override + public void warning(SAXParseException exception) { + log.warn("warning while parsing xml", exception); + } + @Override + public void error(SAXParseException exception) { + errors.add(exception); + } + @Override + public void fatalError(SAXParseException exception) { + error(exception); + } + }; + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(errorHandler); + Document document = db.parse(xmlInputStream); + if ( !errors.isEmpty()) throw new MappingException( "invalid override definition", errors.get( 0 ) ); + add( document ); + return this; + } + catch ( MappingException me ) { + throw me; + } + catch ( Exception e ) { + log.error( "Could not configure overrides from input stream", e ); + throw new MappingException( e ); + } + } + + public void addInputStream(File file) throws MappingException { + try (InputStream xmlInputStream = new FileInputStream( file )) { + try { + addInputStream( xmlInputStream ); + } + catch (Exception e) { + log.error( "Could not configure overrides from input stream", e ); + throw new MappingException( e ); + } + } + catch (IOException ioe) { + log.error( "could not close input stream", ioe ); + } + } + + private void add(Document doc) { + OverrideBinder.bindRoot(this, doc); + } + + private String getPreferredHibernateType(int sqlType, int length, int precision, int scale, boolean nullable) { + List l = typeMappings.get(new TypeMappingKey(sqlType,length) ); + + if(l == null) { // if no precise length match found, then try to find matching unknown length matches + l = typeMappings.get(new TypeMappingKey(sqlType,SQLTypeMapping.UNKNOWN_LENGTH) ); + } + return scanForMatch( sqlType, length, precision, scale, nullable, l ); + } + + private String scanForMatch(int sqlType, int length, int precision, int scale, boolean nullable, List l) { + if(l!=null) { + for ( SQLTypeMapping element : l ) { + if ( element.getJDBCType() != sqlType ) return null; + if ( element.match( sqlType, length, precision, scale, nullable ) ) { + return element.getHibernateType(); + } + } + } + return null; + } + + public void addTypeMapping(SQLTypeMapping sqltype) { + TypeMappingKey key = new TypeMappingKey(sqltype); + List list = typeMappings.computeIfAbsent( key, k -> new ArrayList<>() ); + list.add(sqltype); + } + + static class TypeMappingKey { + + int type; + int length; + + TypeMappingKey(SQLTypeMapping mpa) { + type = mpa.getJDBCType(); + length = mpa.getLength(); + } + + public TypeMappingKey(int sqlType, int length) { + this.type = sqlType; + this.length = length; + } + + public boolean equals(Object obj) { + if(obj==null) return false; + if(!(obj instanceof TypeMappingKey other)) return false; + + + return type==other.type && length==other.length; + } + + public int hashCode() { + return (type + length) % 17; + } + + public String toString() { + return this.getClass() + "(type:" + type + ", length:" + length + ")"; + } + } + + protected String getPackageName(TableIdentifier identifier) { + for ( TableFilter tf : tableFilters ) { + String value = tf.getPackage( identifier ); + if ( value != null ) { + return value; + } + } + return null; + } + + protected boolean excludeTable(TableIdentifier identifier) { + Iterator iterator = tableFilters.iterator(); + boolean hasInclude = false; + + while(iterator.hasNext() ) { + TableFilter tf = iterator.next(); + Boolean value = tf.exclude(identifier); + if(value!=null) { + return value; + } + if(!tf.getExclude() ) { + hasInclude = true; + } + } + + return hasInclude; + } + + public void addTableFilter(TableFilter filter) { + tableFilters.add(filter); + } + + public RevengStrategy getReverseEngineeringStrategy(RevengStrategy delegate) { + return new DelegatingStrategy(delegate) { + + public boolean excludeTable(TableIdentifier ti) { + return OverrideRepository.this.excludeTable(ti); + } + + public Map tableToMetaAttributes(TableIdentifier tableIdentifier) { + return OverrideRepository.this.tableToMetaAttributes(tableIdentifier); + } + + public Map columnToMetaAttributes(TableIdentifier tableIdentifier, String column) { + return OverrideRepository.this.columnToMetaAttributes(tableIdentifier, column); + } + + public boolean excludeColumn(TableIdentifier identifier, String columnName) { + return excludedColumns.contains(new TableColumnKey(identifier, columnName)); + } + + public String tableToCompositeIdName(TableIdentifier identifier) { + String result = compositeIdNameForTable.get(identifier); + if(result==null) { + return super.tableToCompositeIdName(identifier); + } + else { + return result; + } + } + public List getSchemaSelections() { + if(schemaSelections.isEmpty()) { + return super.getSchemaSelections(); + } + else { + return schemaSelections; + } + } + + public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { + String result; + String location = ""; + String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; + if(table!=null) { + location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName; + } + else { + + location += " Column: " + columnName + info; + } + if(table!=null && columnName!=null) { + result = typeForColumn.get(new TableColumnKey(table, columnName)); + if(result!=null) { + log.debug("explicit column mapping found for [" + location + "] to [" + result + "]"); + return result; + } + } + + result = OverrideRepository.this.getPreferredHibernateType(sqlType, length, precision, scale, nullable); + if(result==null) { + return super.columnToHibernateTypeName(table, columnName, sqlType, length, precision, scale, nullable, generatedIdentifier); + } + else { + log.debug(" found for [" + location + info + "] to [" + result + "]"); + return result; + } + } + + public String tableToClassName(TableIdentifier tableIdentifier) { + String className = tableToClassName.get(tableIdentifier); + + if(className!=null) { + if( className.contains( "." ) ) { + return className; + } + else { + String packageName = getPackageName(tableIdentifier); + if(packageName==null) { + return className; + } + else { + return StringHelper.qualify(packageName, className); + } + } + } + + String packageName = getPackageName(tableIdentifier); + if(packageName==null) { + return super.tableToClassName(tableIdentifier); + } + else { + String string = super.tableToClassName(tableIdentifier); + if(string==null) return null; + return StringHelper.qualify(packageName, StringHelper.unqualify(string)); + } + } + + public List getForeignKeys(TableIdentifier referencedTable) { + List list = foreignKeys.get(referencedTable); + if(list==null) { + return super.getForeignKeys(referencedTable); + } + else { + return list; + } + } + + public String columnToPropertyName(TableIdentifier table, String column) { + String result = propertyNameForColumn.get(new TableColumnKey(table, column)); + if(result==null) { + return super.columnToPropertyName(table, column); + } + else { + return result; + } + } + + public String tableToIdentifierPropertyName(TableIdentifier tableIdentifier) { + String result = propertyNameForPrimaryKey.get(tableIdentifier); + if(result==null) { + return super.tableToIdentifierPropertyName(tableIdentifier); + } + else { + return result; + } + } + + public String getTableIdentifierStrategyName(TableIdentifier tableIdentifier) { + String result = identifierStrategyForTable.get(tableIdentifier); + if(result==null) { + return super.getTableIdentifierStrategyName( tableIdentifier ); + } + else { + log.debug("tableIdentifierStrategy for " + tableIdentifier + " -> '" + result + "'"); + return result; + } + } + + public Properties getTableIdentifierProperties(TableIdentifier tableIdentifier) { + Properties result = identifierPropertiesForTable.get(tableIdentifier); + if(result==null) { + return super.getTableIdentifierProperties( tableIdentifier ); + } + else { + return result; + } + } + + public List getPrimaryKeyColumnNames(TableIdentifier tableIdentifier) { + List result = primaryKeyColumnsForTable.get(tableIdentifier); + if(result==null) { + return super.getPrimaryKeyColumnNames(tableIdentifier); + } + else { + return result; + } + } + + public String foreignKeyToEntityName(String keyname, TableIdentifier fromTable, List fromColumnNames, TableIdentifier referencedTable, List referencedColumnNames, boolean uniqueReference) { + String property = foreignKeyToOneName.get(keyname); + if(property==null) { + return super.foreignKeyToEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); + } + else { + return property; + } + } + + + public String foreignKeyToInverseEntityName(String keyname, + TableIdentifier fromTable, List fromColumnNames, + TableIdentifier referencedTable, + List referencedColumnNames, boolean uniqueReference) { + + String property = foreignKeyToInverseName.get(keyname); + if(property==null) { + return super.foreignKeyToInverseEntityName(keyname, fromTable, fromColumnNames, referencedTable, referencedColumnNames, uniqueReference); + } + else { + return property; + } + } + + public String foreignKeyToCollectionName(String keyname, TableIdentifier fromTable, List fromColumns, TableIdentifier referencedTable, List referencedColumns, boolean uniqueReference) { + String property = foreignKeyToInverseName.get(keyname); + if(property==null) { + return super.foreignKeyToCollectionName(keyname, fromTable, fromColumns, referencedTable, referencedColumns, uniqueReference); + } + else { + return property; + } + } + + public boolean excludeForeignKeyAsCollection( + String keyname, + TableIdentifier fromTable, + List fromColumns, + TableIdentifier referencedTable, + List referencedColumns) { + Boolean bool = foreignKeyInverseExclude.get(keyname); + return Objects.requireNonNullElseGet(bool, () -> super.excludeForeignKeyAsCollection(keyname, fromTable, fromColumns, + referencedTable, referencedColumns)); + } + + public boolean excludeForeignKeyAsManytoOne( + String keyname, + TableIdentifier fromTable, + List fromColumns, TableIdentifier + referencedTable, + List referencedColumns) { + Boolean bool = foreignKeyToOneExclude.get(keyname); + return Objects.requireNonNullElseGet(bool, () -> super.excludeForeignKeyAsManytoOne(keyname, fromTable, fromColumns, + referencedTable, referencedColumns)); + } + + + public AssociationInfo foreignKeyToInverseAssociationInfo(ForeignKey foreignKey) { + AssociationInfo fkei = foreignKeyToInverseEntityInfo.get(foreignKey.getName()); + if(fkei!=null) { + return fkei; + } + else { + return super.foreignKeyToInverseAssociationInfo(foreignKey); + } + } + + public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) { + AssociationInfo fkei = foreignKeyToEntityInfo.get(foreignKey.getName()); + if(fkei!=null) { + return fkei; + } + else { + return super.foreignKeyToAssociationInfo(foreignKey); + } + } + }; + } + + protected Map columnToMetaAttributes(TableIdentifier tableIdentifier, String column) { + MultiValuedMap specific = columnMetaAttributes.get( new TableColumnKey(tableIdentifier, column) ); + if(specific!=null && !specific.isEmpty()) { + return toMetaAttributes(specific); + } + + return null; + } + + // TODO: optimize + protected Map tableToMetaAttributes(TableIdentifier identifier) { + MultiValuedMap specific = tableMetaAttributes.get( identifier ); + if(specific!=null && !specific.isEmpty()) { + return toMetaAttributes(specific); + } + MultiValuedMap general = findGeneralAttributes( identifier ); + if(general!=null && !general.isEmpty()) { + return toMetaAttributes(general); + } + + return null; /* inheritance not defined yet - if(specific==null) { specific = Collections.EMPTY_MAP; } + if(specific==null) { specific = Collections.EMPTY_MAP; } if(general==null) { general = Collections.EMPTY_MAP; } MultiMap map = MetaAttributeBinder.mergeMetaMaps( specific, general ); @@ -567,137 +560,140 @@ protected Map tableToMetaAttributes(TableIdentifier identi /* if(map!=null && !map.isEmpty()) { return toMetaAttributes(null, map); - } else { + } + else { return null; } */ - } - - private MultiValuedMap findGeneralAttributes(TableIdentifier identifier) { - for ( TableFilter tf : tableFilters ) { - MultiValuedMap value = tf.getMetaAttributes( identifier ); - if ( value != null ) { - return value; - } - } - return null; - } - - private Map toMetaAttributes(MultiValuedMap mvm) { - Map result = new HashMap(); - for (MapIterator iter = mvm.mapIterator(); iter.hasNext();) { - String key = iter.next(); - Collection values = mvm.get(key); - result.put(key, MetaAttributeHelper.toRealMetaAttribute(key, values)); - } - return result; - } - - /** - * @deprecated Use {@link #getReverseEngineeringStrategy(RevengStrategy)} - * with {@code delegate=null} to explicitly ignore the delegate. - */ - @Deprecated - public RevengStrategy getReverseEngineeringStrategy() { - return getReverseEngineeringStrategy(null); - } - - public void addTable(Table table, String wantedClassName) { - for (ForeignKey fk : table.getForeignKeys().values()) { - TableIdentifier identifier = TableIdentifier.create(fk.getReferencedTable()); - List existing = foreignKeys.computeIfAbsent( identifier, k -> new ArrayList<>() ); - existing.add( fk ); - } - - if(StringHelper.isNotEmpty(wantedClassName)) { - TableIdentifier tableIdentifier = TableIdentifier.create(table); - String className = wantedClassName; - /* If wantedClassName specifies a package, it is given by -
config so do no more. */ - if(!wantedClassName.contains(".")) { - /* Now look for the package name specified by - config. */ - String packageName = getPackageName(tableIdentifier); - if (packageName != null && !packageName.isBlank()) { - className = packageName + "." + wantedClassName; - } - } - tableToClassName.put(tableIdentifier, className); - } - } - - static class TableColumnKey { - private final TableIdentifier query; - private final String name; - - TableColumnKey(TableIdentifier query, String name){ - this.query = query; - this.name = name; - } - - @Override - public int hashCode() { - final int prime = 29; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((query == null) ? 0 : query.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - TableColumnKey other = (TableColumnKey) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (query == null) { - return other.query == null; - } else return query.equals( other.query ); - } - - } - - public void setTypeNameForColumn(TableIdentifier identifier, String columnName, String type) { - if(StringHelper.isNotEmpty(type)) { - typeForColumn.put(new TableColumnKey(identifier, columnName), type); - } - } - - public void setExcludedColumn(TableIdentifier tableIdentifier, String columnName) { - excludedColumns.add(new TableColumnKey(tableIdentifier, columnName)); - } - - public void setPropertyNameForColumn(TableIdentifier identifier, String columnName, String property) { - if(StringHelper.isNotEmpty(property)) { - propertyNameForColumn.put(new TableColumnKey(identifier, columnName), property); - } - } - - public void addTableIdentifierStrategy(Table table, String identifierClass, Properties params) { - if(identifierClass!=null) { - final TableIdentifier tid = TableIdentifier.create(table); - identifierStrategyForTable.put(tid, identifierClass); - identifierPropertiesForTable.put(tid, params); - } - } - - public void addPrimaryKeyNamesForTable(Table table, List boundColumnNames, String propertyName, String compositeIdName) { - TableIdentifier tableIdentifier = TableIdentifier.create(table); - if(boundColumnNames!=null && !boundColumnNames.isEmpty()) { - primaryKeyColumnsForTable.put(tableIdentifier, boundColumnNames); - } - if(StringHelper.isNotEmpty(propertyName)) { - propertyNameForPrimaryKey.put(tableIdentifier, propertyName); - } - if(StringHelper.isNotEmpty(compositeIdName)) { - compositeIdNameForTable.put(tableIdentifier, compositeIdName); - } - } + } + + private MultiValuedMap findGeneralAttributes(TableIdentifier identifier) { + for ( TableFilter tf : tableFilters ) { + MultiValuedMap value = tf.getMetaAttributes( identifier ); + if ( value != null ) { + return value; + } + } + return null; + } + + private Map toMetaAttributes(MultiValuedMap mvm) { + Map result = new HashMap<>(); + for (MapIterator iter = mvm.mapIterator(); iter.hasNext();) { + String key = iter.next(); + Collection values = mvm.get(key); + result.put(key, MetaAttributeHelper.toRealMetaAttribute(key, values)); + } + return result; + } + + /** + * @deprecated Use {@link #getReverseEngineeringStrategy(RevengStrategy)} + * with {@code delegate=null} to explicitly ignore the delegate. + */ + @Deprecated + public RevengStrategy getReverseEngineeringStrategy() { + return getReverseEngineeringStrategy(null); + } + + public void addTable(Table table, String wantedClassName) { + for (ForeignKey fk : table.getForeignKeyCollection()) { + TableIdentifier identifier = TableIdentifier.create(fk.getReferencedTable()); + List existing = foreignKeys.computeIfAbsent( identifier, k -> new ArrayList<>() ); + existing.add( fk ); + } + + if(StringHelper.isNotEmpty(wantedClassName)) { + TableIdentifier tableIdentifier = TableIdentifier.create(table); + String className = wantedClassName; + /* If wantedClassName specifies a package, it is given by +
config so do no more. */ + if(!wantedClassName.contains(".")) { + /* Now look for the package name specified by + config. */ + String packageName = getPackageName(tableIdentifier); + if (packageName != null && !packageName.isBlank()) { + className = packageName + "." + wantedClassName; + } + } + tableToClassName.put(tableIdentifier, className); + } + } + + static class TableColumnKey { + private final TableIdentifier query; + private final String name; + + TableColumnKey(TableIdentifier query, String name){ + this.query = query; + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 29; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((query == null) ? 0 : query.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + TableColumnKey other = (TableColumnKey) obj; + if (name == null) { + if (other.name != null) + return false; + } + else if (!name.equals(other.name)) + return false; + if (query == null) { + return other.query == null; + } + else return query.equals( other.query ); + } + + } + + public void setTypeNameForColumn(TableIdentifier identifier, String columnName, String type) { + if(StringHelper.isNotEmpty(type)) { + typeForColumn.put(new TableColumnKey(identifier, columnName), type); + } + } + + public void setExcludedColumn(TableIdentifier tableIdentifier, String columnName) { + excludedColumns.add(new TableColumnKey(tableIdentifier, columnName)); + } + + public void setPropertyNameForColumn(TableIdentifier identifier, String columnName, String property) { + if(StringHelper.isNotEmpty(property)) { + propertyNameForColumn.put(new TableColumnKey(identifier, columnName), property); + } + } + + public void addTableIdentifierStrategy(Table table, String identifierClass, Properties params) { + if(identifierClass!=null) { + final TableIdentifier tid = TableIdentifier.create(table); + identifierStrategyForTable.put(tid, identifierClass); + identifierPropertiesForTable.put(tid, params); + } + } + + public void addPrimaryKeyNamesForTable(Table table, List boundColumnNames, String propertyName, String compositeIdName) { + TableIdentifier tableIdentifier = TableIdentifier.create(table); + if(boundColumnNames!=null && !boundColumnNames.isEmpty()) { + primaryKeyColumnsForTable.put(tableIdentifier, boundColumnNames); + } + if(StringHelper.isNotEmpty(propertyName)) { + propertyNameForPrimaryKey.put(tableIdentifier, propertyName); + } + if(StringHelper.isNotEmpty(compositeIdName)) { + compositeIdNameForTable.put(tableIdentifier, compositeIdName); + } + } /*public String getCatalog(String string) { return string==null?defaultCatalog:string; @@ -707,107 +703,109 @@ public void addPrimaryKeyNamesForTable(Table table, List boundColumnName return string==null?defaultSchema:string; }*/ - public void addSchemaSelection(SchemaSelection schemaSelection) { - schemaSelections.add(schemaSelection); - } - - /** - * Both sides of the FK are important, - * the owning side can generate a toOne (ManyToOne or OneToOne), we call this side foreignKeyToOne - * the inverse side can generate a OneToMany OR a OneToOne (in case we have a pure bidirectional OneToOne, we call this side foreignKeyToInverse - */ - public void addForeignKeyInfo(String constraintName, String toOneProperty, Boolean excludeToOne, String inverseProperty, Boolean excludeInverse, AssociationInfo associationInfo, AssociationInfo inverseAssociationInfo) { - if(StringHelper.isNotEmpty(toOneProperty)) { - foreignKeyToOneName.put(constraintName, toOneProperty); - } - if(StringHelper.isNotEmpty(inverseProperty)) { - foreignKeyToInverseName.put(constraintName, inverseProperty); - } - if(excludeInverse!=null) { - foreignKeyInverseExclude.put(constraintName, excludeInverse); - } - if(excludeToOne!=null) { - foreignKeyToOneExclude.put(constraintName, excludeToOne); - } - if(associationInfo!=null) { - foreignKeyToEntityInfo.put(constraintName, associationInfo); - } - if(inverseAssociationInfo!=null) { - foreignKeyToInverseEntityInfo.put(constraintName, inverseAssociationInfo); - } - - } - - public void addMetaAttributeInfo(Table table, MultiValuedMap map) { - if(map!=null && !map.isEmpty()) { - tableMetaAttributes.put(TableIdentifier.create(table), map); - } - - } - - public void addMetaAttributeInfo( - TableIdentifier tableIdentifier, - String name, - MultiValuedMap map) { - if(map!=null && !map.isEmpty()) { - columnMetaAttributes.put(new TableColumnKey( tableIdentifier, name ), map); - } - - } - - /*It is not possible to match a table on TableMapper alone because RootClassBinder.bind() - calls nullifyDefaultCatalogAndSchema(table) before doing this TableToClassName lookup. - So only use the table name for initial matching, and catalog or schema names when they - are not null. - */ - - private static class TableToClassName { - Map map = new HashMap(); - - private String get(TableIdentifier tableIdentifier) { - TableMapper mapper = map.get(tableIdentifier.getName()); - if (mapper != null) { - if (mapper.catalog == null || tableIdentifier.getCatalog() == null || - mapper.catalog.equals(tableIdentifier.getCatalog())){ - if (mapper.schema == null || tableIdentifier.getSchema() == null || - mapper.schema.equals(tableIdentifier.getSchema())){ - if ( mapper.packageName.isEmpty() ) { - return mapper.className; - } else { - return mapper.packageName + "." + mapper.className; - } - } - } - } - return null; - } - - private void put(TableIdentifier tableIdentifier, String wantedClassName) { - TableMapper tableMapper = new TableMapper( - tableIdentifier.getCatalog(), - tableIdentifier.getSchema(), - wantedClassName ); - map.put(tableIdentifier.getName(), tableMapper); - } - } - - private static class TableMapper { - String catalog; - String schema; - String className; - String packageName; - - private TableMapper(String catalog, String schema, String wantedClassName) { - this.catalog = catalog; - this.schema = schema; - if (wantedClassName.contains(".")) { - int nameStartPos = wantedClassName.lastIndexOf("."); - this.className = wantedClassName.substring(nameStartPos+1); - this.packageName = wantedClassName.substring(0, nameStartPos); - } else { - this.className = wantedClassName; - this.packageName = ""; - } - } - } + public void addSchemaSelection(SchemaSelection schemaSelection) { + schemaSelections.add(schemaSelection); + } + + /** + * Both sides of the FK are important, + * the owning side can generate a toOne (ManyToOne or OneToOne), we call this side foreignKeyToOne + * the inverse side can generate a OneToMany OR a OneToOne (in case we have a pure bidirectional OneToOne, we call this side foreignKeyToInverse + */ + public void addForeignKeyInfo(String constraintName, String toOneProperty, Boolean excludeToOne, String inverseProperty, Boolean excludeInverse, AssociationInfo associationInfo, AssociationInfo inverseAssociationInfo) { + if(StringHelper.isNotEmpty(toOneProperty)) { + foreignKeyToOneName.put(constraintName, toOneProperty); + } + if(StringHelper.isNotEmpty(inverseProperty)) { + foreignKeyToInverseName.put(constraintName, inverseProperty); + } + if(excludeInverse!=null) { + foreignKeyInverseExclude.put(constraintName, excludeInverse); + } + if(excludeToOne!=null) { + foreignKeyToOneExclude.put(constraintName, excludeToOne); + } + if(associationInfo!=null) { + foreignKeyToEntityInfo.put(constraintName, associationInfo); + } + if(inverseAssociationInfo!=null) { + foreignKeyToInverseEntityInfo.put(constraintName, inverseAssociationInfo); + } + + } + + public void addMetaAttributeInfo(Table table, MultiValuedMap map) { + if(map!=null && !map.isEmpty()) { + tableMetaAttributes.put(TableIdentifier.create(table), map); + } + + } + + public void addMetaAttributeInfo( + TableIdentifier tableIdentifier, + String name, + MultiValuedMap map) { + if(map!=null && !map.isEmpty()) { + columnMetaAttributes.put(new TableColumnKey( tableIdentifier, name ), map); + } + + } + +/*It is not possible to match a table on TableMapper alone because RootClassBinder.bind() +calls nullifyDefaultCatalogAndSchema(table) before doing this TableToClassName lookup. +So only use the table name for initial matching, and catalog or schema names when they +are not null. +*/ + + private static class TableToClassName { + Map map = new HashMap<>(); + + private String get(TableIdentifier tableIdentifier) { + TableMapper mapper = map.get(tableIdentifier.getName()); + if (mapper != null) { + if (mapper.catalog == null || tableIdentifier.getCatalog() == null || + mapper.catalog.equals(tableIdentifier.getCatalog())){ + if (mapper.schema == null || tableIdentifier.getSchema() == null || + mapper.schema.equals(tableIdentifier.getSchema())){ + if ( mapper.packageName.isEmpty() ) { + return mapper.className; + } + else { + return mapper.packageName + "." + mapper.className; + } + } + } + } + return null; + } + + private void put(TableIdentifier tableIdentifier, String wantedClassName) { + TableMapper tableMapper = new TableMapper( + tableIdentifier.getCatalog(), + tableIdentifier.getSchema(), + wantedClassName ); + map.put(tableIdentifier.getName(), tableMapper); + } + } + + private static class TableMapper { + String catalog; + String schema; + String className; + String packageName; + + private TableMapper(String catalog, String schema, String wantedClassName) { + this.catalog = catalog; + this.schema = schema; + if (wantedClassName.contains(".")) { + int nameStartPos = wantedClassName.lastIndexOf("."); + this.className = wantedClassName.substring(nameStartPos+1); + this.packageName = wantedClassName.substring(0, nameStartPos); + } + else { + this.className = wantedClassName; + this.packageName = ""; + } + } + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/SQLTypeMapping.java b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/SQLTypeMapping.java index c664289227..8c736c59c3 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/SQLTypeMapping.java +++ b/orm/src/main/java/org/hibernate/tool/internal/reveng/strategy/SQLTypeMapping.java @@ -19,149 +19,148 @@ public class SQLTypeMapping implements Comparable { - //static public final int UNKNOWN_TYPE = Integer.MAX_VALUE; - public static final int UNKNOWN_LENGTH = Integer.MAX_VALUE; - public static final int UNKNOWN_PRECISION = Integer.MAX_VALUE; - public static final int UNKNOWN_SCALE = Integer.MAX_VALUE; - public static final Boolean UNKNOWN_NULLABLE = null; - - private final int jdbcType; - private int length = UNKNOWN_LENGTH; - private int precision = UNKNOWN_PRECISION; - private int scale = UNKNOWN_SCALE; - private Boolean nullable; - - private String hibernateType; - - public SQLTypeMapping(int jdbcType) { - this.jdbcType = jdbcType; - } - - /*public void setJDBCType(int jdbcType) { - this.jdbcType = jdbcType; - }*/ - - public SQLTypeMapping(int sqlType, int length, int precision, int scale, Boolean nullable) { - this.jdbcType = sqlType; - this.length = length; - this.precision = precision; - this.scale = scale; - this.nullable = nullable; - } - - public void setLength(int length) { - this.length = length; - } - - public void setHibernateType(String hibernateType) { - this.hibernateType = hibernateType; - } - - public void setNullable(Boolean nullable) { - this.nullable = nullable; - } - - public Boolean getNullable() { - return nullable; - } - - public int getJDBCType() { - return jdbcType; - } - - public String getHibernateType() { - return hibernateType; - } - - public int getLength() { - return length; - } - - public String toString() { - return getJDBCType() + " l:" + getLength() + " p:" + getPrecision() + " s:" + getScale() + " n:" + getNullable() + " ht:" + getHibernateType(); - } - - public int getPrecision() { - return precision; - } - - public void setPrecision(int precision) { - this.precision = precision; - } - - public int getScale() { - return scale; - } - - public void setScale(int scale) { - this.scale = scale; - } - - public boolean match(int matchjdbctype, int matchlength, int matchprecision, int matchscale, boolean matchnullable) { - if(matchjdbctype==this.jdbcType) {// this always need to be exact - if(matchlength==this.length || this.length == UNKNOWN_LENGTH) { - if(matchprecision==this.precision || this.precision == UNKNOWN_PRECISION) { - if(matchscale==this.scale || this.scale == UNKNOWN_SCALE ) { - return this.nullable == UNKNOWN_NULLABLE || nullable.equals( matchnullable ); - } - } - } - } - return false; - } - - public int compareTo(SQLTypeMapping other) { - if(this.jdbcType==other.jdbcType) { - if(this.length==other.length) { - if(this.precision==other.precision) { - if(this.scale==other.scale) { - return compare(this.nullable, other.nullable); - } else { - return compare(this.scale, other.scale); - } - } - else { - return compare(this.precision,other.precision); - } - } - else { - return compare(this.length,other.length); - } - } - else { - return compare(this.jdbcType,other.jdbcType); - } - } - - private int compare(int value, int other) { - return Integer.compare( value, other ); - } - - // complete ordering of the tri-state: false, true, UNKNOWN_NULLABLE - private int compare(Boolean value, Boolean other) { - if(value==other) return 0; - if(value==UNKNOWN_NULLABLE) return 1; - if(other==UNKNOWN_NULLABLE) return -1; - if(value.equals(other)) return 0; - if(value.equals(Boolean.TRUE)) { - return 1; - } else { - return -1; - } - } - - public boolean equals(Object obj) { - if (getClass().isAssignableFrom(obj.getClass())) { - SQLTypeMapping other = getClass().cast(obj); - return compareTo(other)==0; - } else { - return false; - } - } - - public int hashCode() { - return (jdbcType + length + precision + scale + (nullable==UNKNOWN_NULLABLE?1:nullable.hashCode())) % 17; - } + //static public final int UNKNOWN_TYPE = Integer.MAX_VALUE; + public static final int UNKNOWN_LENGTH = Integer.MAX_VALUE; + public static final int UNKNOWN_PRECISION = Integer.MAX_VALUE; + public static final int UNKNOWN_SCALE = Integer.MAX_VALUE; + public static final Boolean UNKNOWN_NULLABLE = null; + + private final int jdbcType; + private int length = UNKNOWN_LENGTH; + private int precision = UNKNOWN_PRECISION; + private int scale = UNKNOWN_SCALE; + private Boolean nullable; + + private String hibernateType; + + public SQLTypeMapping(int jdbcType) { + this.jdbcType = jdbcType; + } + + public SQLTypeMapping(int sqlType, int length, int precision, int scale, Boolean nullable) { + this.jdbcType = sqlType; + this.length = length; + this.precision = precision; + this.scale = scale; + this.nullable = nullable; + } + + public void setLength(int length) { + this.length = length; + } + + public void setHibernateType(String hibernateType) { + this.hibernateType = hibernateType; + } + + public void setNullable(Boolean nullable) { + this.nullable = nullable; + } + + public Boolean getNullable() { + return nullable; + } + + public int getJDBCType() { + return jdbcType; + } + + public String getHibernateType() { + return hibernateType; + } + + public int getLength() { + return length; + } + + public String toString() { + return getJDBCType() + " l:" + getLength() + " p:" + getPrecision() + " s:" + getScale() + " n:" + getNullable() + " ht:" + getHibernateType(); + } + + public int getPrecision() { + return precision; + } + + public void setPrecision(int precision) { + this.precision = precision; + } + + public int getScale() { + return scale; + } + + public void setScale(int scale) { + this.scale = scale; + } + + public boolean match(int matchjdbctype, int matchlength, int matchprecision, int matchscale, boolean matchnullable) { + if(matchjdbctype==this.jdbcType) {// this always need to be exact + if(matchlength==this.length || this.length == UNKNOWN_LENGTH) { + if(matchprecision==this.precision || this.precision == UNKNOWN_PRECISION) { + if(matchscale==this.scale || this.scale == UNKNOWN_SCALE ) { + return this.nullable == UNKNOWN_NULLABLE || nullable.equals( matchnullable ); + } + } + } + } + return false; + } + + public int compareTo(SQLTypeMapping other) { + if(this.jdbcType==other.jdbcType) { + if(this.length==other.length) { + if(this.precision==other.precision) { + if(this.scale==other.scale) { + return compare(this.nullable, other.nullable); + } + else { + return compare(this.scale, other.scale); + } + } + else { + return compare(this.precision,other.precision); + } + } + else { + return compare(this.length,other.length); + } + } + else { + return compare(this.jdbcType,other.jdbcType); + } + } + + private int compare(int value, int other) { + return Integer.compare( value, other ); + } + + // complete ordering of the tri-state: false, true, UNKNOWN_NULLABLE + private int compare(Boolean value, Boolean other) { + if(value==other) return 0; + if(value==UNKNOWN_NULLABLE) return 1; + if(other==UNKNOWN_NULLABLE) return -1; + if(value.equals(other)) return 0; + if(value.equals(Boolean.TRUE)) { + return 1; + } + else { + return -1; + } + } + + public boolean equals(Object obj) { + if (getClass().isAssignableFrom(obj.getClass())) { + SQLTypeMapping other = getClass().cast(obj); + return compareTo(other)==0; + } + else { + return false; + } + } + + public int hashCode() { + return (jdbcType + length + precision + scale + (nullable==UNKNOWN_NULLABLE?1:nullable.hashCode())) % 17; + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/stat/StatisticsTreeModel.java b/orm/src/main/java/org/hibernate/tool/internal/stat/StatisticsTreeModel.java index ed66e6c8b6..549f5249ed 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/stat/StatisticsTreeModel.java +++ b/orm/src/main/java/org/hibernate/tool/internal/stat/StatisticsTreeModel.java @@ -27,89 +27,97 @@ public class StatisticsTreeModel extends AbstractTreeModel { - private final Statistics stats; - - String queries = "Queries"; - String entities = "Entities"; - String collections = "Collections"; - String secondlevelcache = "Cache"; - - Map im = IdentityMap.instantiateSequenced( 10 ); - - public StatisticsTreeModel(Statistics stats) { - this.stats = stats; - } - - public Object getChild(Object parent, int index) { - if(parent==stats) { - switch(index) { - case 0: return entities; - case 1: return collections; - case 2: return queries; - case 3: return secondlevelcache; - } - } else if(parent==entities) { - return stats.getEntityStatistics(stats.getEntityNames()[index]); - } else if(parent==collections) { - return stats.getCollectionStatistics(stats.getCollectionRoleNames()[index]); - } else if(parent==queries) { - return stats.getQueryStatistics(stats.getQueries()[index]); - } else if(parent==secondlevelcache) { - return stats.getCacheRegionStatistics(stats.getSecondLevelCacheRegionNames()[index]); - } else if (parent instanceof CacheRegionStatistics) { - return Collections.emptyMap(); - } - return null; - } - - public int getChildCount(Object parent) { - if(parent==stats) { - return 4; - } else if(parent==entities) { - return stats.getEntityNames().length; - } else if(parent==collections) { - return stats.getCollectionRoleNames().length; - } else if(parent==queries) { - return stats.getQueries().length; - } else if(parent==secondlevelcache) { - return stats.getSecondLevelCacheRegionNames().length; - } else if(parent instanceof CacheRegionStatistics) { - return 0; - } - return 0; - } - - public int getIndexOfChild(Object parent, Object child) { - throw new IllegalAccessError(); - //return 0; - } - - public Object getRoot() { - return stats; - } - - public boolean isLeaf(Object node) { - return false; - } - - public boolean isQueries(Object o) { - return o==queries; // hack - } - - public boolean isCollections(Object o) { - return o==collections; // hack - } - - public boolean isEntities(Object o) { - return o==entities; // hack - } - - public boolean isCache(Object o) { - return o==secondlevelcache; - } - - public boolean isContainer(Object o) { - return isEntities( o ) || isQueries( o ) || isCollections( o ) || isCache( o ); - } - -} \ No newline at end of file + private final Statistics stats; + + String queries = "Queries"; + String entities = "Entities"; + String collections = "Collections"; + String secondlevelcache = "Cache"; + + public StatisticsTreeModel(Statistics stats) { + this.stats = stats; + } + + public Object getChild(Object parent, int index) { + if(parent==stats) { + switch(index) { + case 0: return entities; + case 1: return collections; + case 2: return queries; + case 3: return secondlevelcache; + } + } + else if(parent==entities) { + return stats.getEntityStatistics(stats.getEntityNames()[index]); + } + else if(parent==collections) { + return stats.getCollectionStatistics(stats.getCollectionRoleNames()[index]); + } + else if(parent==queries) { + return stats.getQueryStatistics(stats.getQueries()[index]); + } + else if(parent==secondlevelcache) { + return stats.getCacheRegionStatistics(stats.getSecondLevelCacheRegionNames()[index]); + } + else if (parent instanceof CacheRegionStatistics) { + return Collections.emptyMap(); + } + return null; + } + + public int getChildCount(Object parent) { + if(parent==stats) { + return 4; + } + else if(parent==entities) { + return stats.getEntityNames().length; + } + else if(parent==collections) { + return stats.getCollectionRoleNames().length; + } + else if(parent==queries) { + return stats.getQueries().length; + } + else if(parent==secondlevelcache) { + return stats.getSecondLevelCacheRegionNames().length; + } + else if(parent instanceof CacheRegionStatistics) { + return 0; + } + return 0; + } + + public int getIndexOfChild(Object parent, Object child) { + throw new IllegalAccessError(); + //return 0; + } + + public Object getRoot() { + return stats; + } + + public boolean isLeaf(Object node) { + return false; + } + + public boolean isQueries(Object o) { + return o==queries; // hack + } + + public boolean isCollections(Object o) { + return o==collections; // hack + } + + public boolean isEntities(Object o) { + return o==entities; // hack + } + + public boolean isCache(Object o) { + return o==secondlevelcache; + } + + public boolean isContainer(Object o) { + return isEntities( o ) || isQueries( o ) || isCollections( o ) || isCache( o ); + } + +} diff --git a/orm/src/main/java/org/hibernate/tool/internal/util/AnnotationBuilder.java b/orm/src/main/java/org/hibernate/tool/internal/util/AnnotationBuilder.java index 0da8bb7e0d..6b86f82843 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/util/AnnotationBuilder.java +++ b/orm/src/main/java/org/hibernate/tool/internal/util/AnnotationBuilder.java @@ -25,136 +25,136 @@ public class AnnotationBuilder { - String annotation; - LinkedHashMap attributes = new LinkedHashMap(); - - public static AnnotationBuilder createAnnotation(String annotation) { - return new AnnotationBuilder(annotation); - } - - protected AnnotationBuilder(String annotation) { - this.annotation = annotation; - } - - public AnnotationBuilder addAttribute(String name, String[] values) { - if(values!=null && values.length > 0) { - attributes.put(name, values); - } - return this; - } - - public AnnotationBuilder addAttribute(String name, String value) { - if(value!=null) { - addAttribute(name, new String[] { value }); - } - return this; - } - - - public AnnotationBuilder resetAnnotation(String annotationName) { - this.annotation = annotationName; - clearAttributes(); - return this; - } - - private AnnotationBuilder clearAttributes() { - attributes.clear(); - return this; - } - - public String getResult() { - StringBuffer b = new StringBuffer("@"); - b.append(annotation); - if(attributes.isEmpty()) { - return b.toString(); - } else { - b.append("("); - Iterator> elements = attributes.entrySet().iterator(); - boolean addedBefore = false; - while ( elements.hasNext() ) { - Entry element = elements.next(); - - String[] s = element.getValue(); - if(s.length==0) { - addedBefore = false; - continue; - } else { - if(addedBefore) { - b.append(", "); - } - String key = element.getKey(); - b.append(key).append("="); - attributeToString( b, s ); - - addedBefore=true; - } - } - b.append( ")" ); - } - return b.toString(); - } - - private void attributeToString(StringBuffer buffer, String[] values) { - if(values.length>1) { - buffer.append( "{" ); - } - - for (int i = 0; i < values.length; i++) { - buffer.append(values[i]); - if(i1) { - buffer.append( "}" ); - } - - } - - public void addQuotedAttributes(String name, Iterator iterator) { - List values = new ArrayList(); - while ( iterator.hasNext() ) { - values.add(quote( iterator.next().toString() )); - } - addAttribute(name, values.toArray( new String[values.size()] )); - } - - public void addAttributes(String name, Iterator iterator) { - List values = new ArrayList(); - while ( iterator.hasNext() ) { - String element = iterator.next().toString(); - values.add( element ); - } - addAttribute(name, values.toArray( new String[values.size()] )); - } - private String quote(String element) { - return "\"" + element + "\""; - } - - public AnnotationBuilder addQuotedAttribute(String name, String value) { - if(value!=null) { - addAttribute(name, quote(value)); - } - return this; - } - - - public String toString() { - return getResult(); - } - - public String getAttributeAsString(String name) { - StringBuffer buffer = new StringBuffer(); - String[] object = (String[]) attributes.get( name ); - if(object==null) { - return null; - } else { - attributeToString( buffer, object ); - return buffer.toString(); - } - } - - -} + String annotation; + LinkedHashMap attributes = new LinkedHashMap<>(); + + public static AnnotationBuilder createAnnotation(String annotation) { + return new AnnotationBuilder(annotation); + } + + protected AnnotationBuilder(String annotation) { + this.annotation = annotation; + } + + public AnnotationBuilder addAttribute(String name, String[] values) { + if(values!=null && values.length > 0) { + attributes.put(name, values); + } + return this; + } + + public AnnotationBuilder addAttribute(String name, String value) { + if(value!=null) { + addAttribute(name, new String[] { value }); + } + return this; + } + + + public AnnotationBuilder resetAnnotation(String annotationName) { + this.annotation = annotationName; + clearAttributes(); + return this; + } + + private void clearAttributes() { + attributes.clear(); + } + + public String getResult() { + StringBuffer b = new StringBuffer("@"); + b.append(annotation); + if(attributes.isEmpty()) { + return b.toString(); + } + else { + b.append("("); + Iterator> elements = attributes.entrySet().iterator(); + boolean addedBefore = false; + while ( elements.hasNext() ) { + Entry element = elements.next(); + + String[] s = element.getValue(); + if(s.length==0) { + addedBefore = false; + } + else { + if(addedBefore) { + b.append(", "); + } + String key = element.getKey(); + b.append(key).append("="); + attributeToString( b, s ); + + addedBefore=true; + } + } + b.append( ")" ); + } + return b.toString(); + } + + private void attributeToString(StringBuffer buffer, String[] values) { + if(values.length>1) { + buffer.append( "{" ); + } + for (int i = 0; i < values.length; i++) { + buffer.append(values[i]); + if(i1) { + buffer.append( "}" ); + } + + } + + public void addQuotedAttributes(String name, Iterator iterator) { + List values = new ArrayList<>(); + while ( iterator.hasNext() ) { + values.add(quote( iterator.next().toString() )); + } + addAttribute(name, values.toArray( new String[0] )); + } + + public void addAttributes(String name, Iterator iterator) { + List values = new ArrayList<>(); + while ( iterator.hasNext() ) { + String element = iterator.next().toString(); + values.add( element ); + } + addAttribute(name, values.toArray( new String[0] )); + } + private String quote(String element) { + return "\"" + element + "\""; + } + + public AnnotationBuilder addQuotedAttribute(String name, String value) { + if(value!=null) { + addAttribute(name, quote(value)); + } + return this; + } + + + public String toString() { + return getResult(); + } + + public String getAttributeAsString(String name) { + StringBuffer buffer = new StringBuffer(); + String[] object = attributes.get( name ); + if(object==null) { + return null; + } + else { + attributeToString( buffer, object ); + return buffer.toString(); + } + } + + +} diff --git a/orm/src/main/java/org/hibernate/tool/internal/util/BeanTableModel.java b/orm/src/main/java/org/hibernate/tool/internal/util/BeanTableModel.java index 86f0cb096b..6e0de36a14 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/util/BeanTableModel.java +++ b/orm/src/main/java/org/hibernate/tool/internal/util/BeanTableModel.java @@ -22,6 +22,7 @@ import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.ObjectStreamClass; +import java.io.Serial; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; @@ -30,104 +31,106 @@ public class BeanTableModel extends AbstractTableModel { - private static final long serialVersionUID = - ObjectStreamClass.lookup(BeanTableModel.class).getSerialVersionUID(); - - - protected List list; - - private BeanInfo beanInfo = null; - - private PropertyDescriptor[] descriptors = null; - - public BeanTableModel(List list, Class beanClass) { - this.list = list; - introspect( beanClass ); - } - - private void introspect(Class beanClass) { - try { - this.beanInfo = Introspector.getBeanInfo( beanClass, - Introspector.USE_ALL_BEANINFO ); - //descriptor = beanInfo.getBeanDescriptor(); - descriptors = beanInfo.getPropertyDescriptors(); - } - catch (IntrospectionException ie) { - // ignore - } - - List v = new ArrayList(descriptors.length); - for (int i = 0; i < descriptors.length; i++) { - if(!descriptors[i].getName().equals("class")) { - v.add( descriptors[i] ); - } - } - descriptors = (PropertyDescriptor[]) v.toArray( new PropertyDescriptor[v.size()] ); - - } - - boolean isSingle() { - return list.size()<=1; - } - - public int getRowCount() { - return isSingle() ? descriptors.length : list.size(); - } - - public int getColumnCount() { - return isSingle() ? list.size() + 1 : (descriptors != null ? descriptors.length : 0); - } - - public Object getValueAt(int row, int col) { - if(isSingle()) { - if(col==0) { - return descriptors[row].getDisplayName(); - } else { - return getValue(0, row); - } - } else { - return getValue( row, col ); - } - } - - private Object getValue(int row, int col) { - Object bean = list.get( row ); - Object result = null; - try { - result = descriptors[col].getReadMethod().invoke( bean, (Object[])null ); - } - catch (InvocationTargetException ite) { - ite.printStackTrace(); - } - catch (IllegalAccessException iae) { - iae.printStackTrace(); - } - return result; - } - - public String getColumnName(int col) { - if(isSingle()) { - if(col==0) { - return "Name"; - } else { - return "Value"; - } - } else { - return descriptors[col].getDisplayName(); - } - } - - public Class getColumnClass(int c) { - if(isSingle()) { - return String.class; - } else { - Class propertyType = descriptors[c].getPropertyType(); - - if(propertyType.isPrimitive()) { - return String.class; // to avoid jtable complain about null table renderer. - } else { - return propertyType; - } - } - } -} \ No newline at end of file + @Serial + private static final long serialVersionUID = + ObjectStreamClass.lookup(BeanTableModel.class).getSerialVersionUID(); + + + protected List list; + + private PropertyDescriptor[] descriptors = null; + + public BeanTableModel(List list, Class beanClass) { + this.list = list; + introspect( beanClass ); + } + + private void introspect(Class beanClass) { + try { + BeanInfo beanInfo = Introspector.getBeanInfo( beanClass, + Introspector.USE_ALL_BEANINFO ); + //descriptor = beanInfo.getBeanDescriptor(); + descriptors = beanInfo.getPropertyDescriptors(); + } + catch (IntrospectionException ie) { + // ignore + } + + List v = new ArrayList<>( descriptors.length ); + for ( PropertyDescriptor descriptor : descriptors ) { + if ( !descriptor.getName().equals( "class" ) ) { + v.add( descriptor ); + } + } + descriptors = v.toArray( new PropertyDescriptor[0] ); + + } + + boolean isSingle() { + return list.size()<=1; + } + + public int getRowCount() { + return isSingle() ? descriptors.length : list.size(); + } + + public int getColumnCount() { + return isSingle() ? list.size() + 1 : (descriptors != null ? descriptors.length : 0); + } + + public Object getValueAt(int row, int col) { + if(isSingle()) { + if(col==0) { + return descriptors[row].getDisplayName(); + } + else { + return getValue(0, row); + } + } + else { + return getValue( row, col ); + } + } + + private Object getValue(int row, int col) { + Object bean = list.get( row ); + Object result; + try { + result = descriptors[col].getReadMethod().invoke( bean, (Object[])null ); + } + catch (InvocationTargetException | IllegalAccessException e) { + throw new RuntimeException(e); + } + return result; + } + + public String getColumnName(int col) { + if(isSingle()) { + if(col==0) { + return "Name"; + } + else { + return "Value"; + } + } + else { + return descriptors[col].getDisplayName(); + } + } + + public Class getColumnClass(int c) { + if(isSingle()) { + return String.class; + } + else { + Class propertyType = descriptors[c].getPropertyType(); + + if(propertyType.isPrimitive()) { + return String.class; // to avoid jtable complain about null table renderer. + } + else { + return propertyType; + } + } + } +} diff --git a/orm/src/main/java/org/hibernate/tool/internal/util/JdbcToHibernateTypeHelper.java b/orm/src/main/java/org/hibernate/tool/internal/util/JdbcToHibernateTypeHelper.java index 3f1f664997..9a8242a625 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/util/JdbcToHibernateTypeHelper.java +++ b/orm/src/main/java/org/hibernate/tool/internal/util/JdbcToHibernateTypeHelper.java @@ -34,191 +34,178 @@ * */ public final class JdbcToHibernateTypeHelper { - - private JdbcToHibernateTypeHelper() { - - } - - /** The Map containing the preferred conversion type values. */ - private static final Map PREFERRED_HIBERNATETYPE_FOR_SQLTYPE = new HashMap(); - - static { - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TINYINT), new String[] { "byte", Byte.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.SMALLINT), new String[] { "short", Short.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.INTEGER), new String[] { "int", Integer.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BIGINT), new String[] { "long", Long.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.REAL), new String[] { "float", Float.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.FLOAT), new String[] { "double", Double.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DOUBLE), new String[] { "double", Double.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DECIMAL), new String[] { "big_decimal", "big_decimal" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.NUMERIC), new String[] { "big_decimal", "big_decimal" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BIT), new String[] { "boolean", Boolean.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BOOLEAN), new String[] { "boolean", Boolean.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.CHAR), new String[] { "char", Character.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.VARCHAR), new String[] { "string", "string" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.LONGVARCHAR), new String[] { "string", "string" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.VARBINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.LONGVARBINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DATE), new String[] { "date", "date" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TIME), new String[] { "time", "time" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TIMESTAMP), new String[] { "timestamp", "timestamp" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.CLOB), new String[] { "clob", "clob" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BLOB), new String[] { "blob", "blob" }); - - //Hibernate does not have any built-in Type for these: - //preferredJavaTypeForSqlType.put(new Integer(Types.ARRAY), "java.sql.Array"); - //preferredJavaTypeForSqlType.put(new Integer(Types.REF), "java.sql.Ref"); - //preferredJavaTypeForSqlType.put(new Integer(Types.STRUCT), "java.lang.Object"); - //preferredJavaTypeForSqlType.put(new Integer(Types.JAVA_OBJECT), "java.lang.Object"); - } - - /* (non-Javadoc) - * @see org.hibernate.cfg.JDBCTypeToHibernateTypesStrategy#getPreferredHibernateType(int, int, int, int) - */ - public static String getPreferredHibernateType(int sqlType, int size, int precision, int scale, boolean nullable, boolean generatedIdentifier) { - boolean returnNullable = nullable || generatedIdentifier; - if ( (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) && scale <= 0) { // <= - if (precision == 1) { - // NUMERIC(1) is a often used idiom for storing boolean thus providing it out of the box. - return returnNullable?Boolean.class.getName():"boolean"; - } - else if (precision < 3) { - return returnNullable?Byte.class.getName():"byte"; - } - else if (precision < 5) { - return returnNullable?Short.class.getName():"short"; - } - else if (precision < 10) { - return returnNullable?Integer.class.getName():"int"; - } - else if (precision < 19) { - return returnNullable?Long.class.getName():"long"; - } - else { - return "big_integer"; - } - } - - if ( sqlType == Types.CHAR && size>1 ) { - return "string"; - } - - String[] result = (String[]) PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.get(Integer.valueOf(sqlType) ); - - if(result==null) { - return null; - } else if(returnNullable) { - return result[1]; - } else { - return result[0]; - } - } - - static Map jdbcTypes; // Name to value - static Map jdbcTypeValues; // value to Name - - public static String[] getJDBCTypes() { - checkTypes(); - - return (String[]) jdbcTypes.keySet().toArray(new String[jdbcTypes.size()]); - } - - public static int getJDBCType(String value) { - checkTypes(); - - Integer number = (Integer) jdbcTypes.get(value); - - if(number==null) { - try { - return Integer.parseInt(value); - } - catch (NumberFormatException nfe) { - throw new MappingException("jdbc-type: " + value + " is not a known JDBC Type nor a valid number"); - } - } - else { - return number.intValue(); - } - } - - private static void checkTypes() { - if(jdbcTypes==null) { - jdbcTypes = new HashMap(); - Field[] fields = Types.class.getFields(); - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - if(Modifier.isStatic(field.getModifiers() ) ) { - try { - jdbcTypes.put(field.getName(), (Integer)field.get(Types.class) ); - } - catch (IllegalArgumentException e) { - // ignore - } - catch (IllegalAccessException e) { - // ignore - } - } - } - } - } - + + private JdbcToHibernateTypeHelper() { + + } + + /** The Map containing the preferred conversion type values. */ + private static final Map PREFERRED_HIBERNATETYPE_FOR_SQLTYPE = new HashMap<>(); + + static { + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.TINYINT, new String[] { "byte", Byte.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.SMALLINT, new String[] { "short", Short.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.INTEGER, new String[] { "int", Integer.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.BIGINT, new String[] { "long", Long.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.REAL, new String[] { "float", Float.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.FLOAT, new String[] { "double", Double.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.DOUBLE, new String[] { "double", Double.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.DECIMAL, new String[] { "big_decimal", "big_decimal" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.NUMERIC, new String[] { "big_decimal", "big_decimal" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.BIT, new String[] { "boolean", Boolean.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.BOOLEAN, new String[] { "boolean", Boolean.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.CHAR, new String[] { "char", Character.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.VARCHAR, new String[] { "string", "string" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.LONGVARCHAR, new String[] { "string", "string" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.BINARY, new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.VARBINARY, new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.LONGVARBINARY, new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.DATE, new String[] { "date", "date" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.TIME, new String[] { "time", "time" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.TIMESTAMP, new String[] { "timestamp", "timestamp" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.CLOB, new String[] { "clob", "clob" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put( Types.BLOB, new String[] { "blob", "blob" }); + + //Hibernate does not have any built-in Type for these: + //preferredJavaTypeForSqlType.put(new Integer(Types.ARRAY), "java.sql.Array"); + //preferredJavaTypeForSqlType.put(new Integer(Types.REF), "java.sql.Ref"); + //preferredJavaTypeForSqlType.put(new Integer(Types.STRUCT), "java.lang.Object"); + //preferredJavaTypeForSqlType.put(new Integer(Types.JAVA_OBJECT), "java.lang.Object"); + } + + /* (non-Javadoc) + * @see org.hibernate.cfg.JDBCTypeToHibernateTypesStrategy#getPreferredHibernateType(int, int, int, int) + */ + public static String getPreferredHibernateType(int sqlType, int size, int precision, int scale, boolean nullable, boolean generatedIdentifier) { + boolean returnNullable = nullable || generatedIdentifier; + if ( (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC) && scale <= 0) { // <= + if (precision == 1) { + // NUMERIC(1) is a often used idiom for storing boolean thus providing it out of the box. + return returnNullable?Boolean.class.getName():"boolean"; + } + else if (precision < 3) { + return returnNullable?Byte.class.getName():"byte"; + } + else if (precision < 5) { + return returnNullable?Short.class.getName():"short"; + } + else if (precision < 10) { + return returnNullable?Integer.class.getName():"int"; + } + else if (precision < 19) { + return returnNullable?Long.class.getName():"long"; + } + else { + return "big_integer"; + } + } + + if ( sqlType == Types.CHAR && size>1 ) { + return "string"; + } + + String[] result = PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.get( sqlType ); + + if(result==null) { + return null; + } + else if(returnNullable) { + return result[1]; + } + else { + return result[0]; + } + } + + static Map jdbcTypes; // Name to value + static Map jdbcTypeValues; // value to Name + + public static String[] getJDBCTypes() { + checkTypes(); + + return jdbcTypes.keySet().toArray( new String[0] ); + } + + public static int getJDBCType(String value) { + checkTypes(); + + Integer number = jdbcTypes.get(value); + + if(number==null) { + try { + return Integer.parseInt(value); + } + catch (NumberFormatException nfe) { + throw new MappingException("jdbc-type: " + value + " is not a known JDBC Type nor a valid number"); + } + } + else { + return number; + } + } + + private static void checkTypes() { + if(jdbcTypes==null) { + jdbcTypes = new HashMap<>(); + Field[] fields = Types.class.getFields(); + for ( Field field : fields ) { + if ( Modifier.isStatic( field.getModifiers() ) ) { + try { + jdbcTypes.put( field.getName(), (Integer) field.get( Types.class ) ); + } + catch (IllegalArgumentException | IllegalAccessException e) { + // ignore + } + } + } + } + } + public static String getJDBCTypeName(int value) { - if(jdbcTypeValues==null) { - jdbcTypeValues = new HashMap(); - Field[] fields = Types.class.getFields(); - for (int i = 0; i < fields.length; i++) { - Field field = fields[i]; - if(Modifier.isStatic(field.getModifiers() ) ) { - try { - jdbcTypeValues.put((Integer)field.get(Types.class), field.getName() ); - } - catch (IllegalArgumentException e) { - // ignore - } - catch (IllegalAccessException e) { - // ignore - } - } - } - } - - String name = (String) jdbcTypeValues.get(Integer.valueOf(value) ); - - if(name!=null) { - return name; - } - else { - return ""+value; - } - } - - /** - * @param table - * @param schema - * @param catalog - * @throws SQLException - */ - - // scale is for non floating point numeric columns - public static boolean typeHasScale(int sqlType) { - return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC); - } - - // precision is for numeric columns - public static boolean typeHasPrecision(int sqlType) { - return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC - || sqlType == Types.REAL || sqlType == Types.FLOAT || sqlType == Types.DOUBLE); - } - - public static boolean typeHasScaleAndPrecision(int sqlType) { - return typeHasScale(sqlType) && typeHasPrecision(sqlType); - } - - // length is for string columns - public static boolean typeHasLength(int sqlType) { - return (sqlType == Types.CHAR || sqlType == Types.DATE - || sqlType == Types.LONGVARCHAR || sqlType == Types.TIME || sqlType == Types.TIMESTAMP - || sqlType == Types.VARCHAR ); - } + if(jdbcTypeValues==null) { + jdbcTypeValues = new HashMap<>(); + Field[] fields = Types.class.getFields(); + for ( Field field : fields ) { + if ( Modifier.isStatic( field.getModifiers() ) ) { + try { + jdbcTypeValues.put( (Integer) field.get( Types.class ), field.getName() ); + } + catch (IllegalArgumentException | IllegalAccessException e) { + // ignore + } + } + } + } + + String name = jdbcTypeValues.get( value ); + + if(name!=null) { + return name; + } + else { + return ""+value; + } + } + + // scale is for non floating point numeric columns + public static boolean typeHasScale(int sqlType) { + return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC); + } + + // precision is for numeric columns + public static boolean typeHasPrecision(int sqlType) { + return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC + || sqlType == Types.REAL || sqlType == Types.FLOAT || sqlType == Types.DOUBLE); + } + + public static boolean typeHasScaleAndPrecision(int sqlType) { + return typeHasScale(sqlType) && typeHasPrecision(sqlType); + } + + // length is for string columns + public static boolean typeHasLength(int sqlType) { + return (sqlType == Types.CHAR || sqlType == Types.DATE + || sqlType == Types.LONGVARCHAR || sqlType == Types.TIME || sqlType == Types.TIMESTAMP + || sqlType == Types.VARCHAR ); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/util/NameConverter.java b/orm/src/main/java/org/hibernate/tool/internal/util/NameConverter.java index 7a861fbcea..6a6f801b89 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/util/NameConverter.java +++ b/orm/src/main/java/org/hibernate/tool/internal/util/NameConverter.java @@ -22,142 +22,143 @@ final public class NameConverter { - private static final Set RESERVED_KEYWORDS; - static { - RESERVED_KEYWORDS = new HashSet<>(); - - RESERVED_KEYWORDS.add( "abstract" ); - RESERVED_KEYWORDS.add( "continue" ); - RESERVED_KEYWORDS.add( "for" ); - RESERVED_KEYWORDS.add( "new" ); - RESERVED_KEYWORDS.add( "switch" ); - RESERVED_KEYWORDS.add( "assert" ); - RESERVED_KEYWORDS.add( "default" ); - RESERVED_KEYWORDS.add( "goto" ); - RESERVED_KEYWORDS.add( "package" ); - RESERVED_KEYWORDS.add( "synchronized" ); - RESERVED_KEYWORDS.add( "boolean" ); - RESERVED_KEYWORDS.add( "do" ); - RESERVED_KEYWORDS.add( "if" ); - RESERVED_KEYWORDS.add( "private" ); - RESERVED_KEYWORDS.add( "this" ); - RESERVED_KEYWORDS.add( "break" ); - RESERVED_KEYWORDS.add( "double" ); - RESERVED_KEYWORDS.add( "implements" ); - RESERVED_KEYWORDS.add( "protected" ); - RESERVED_KEYWORDS.add( "throw" ); - RESERVED_KEYWORDS.add( "byte" ); - RESERVED_KEYWORDS.add( "else" ); - RESERVED_KEYWORDS.add( "import" ); - RESERVED_KEYWORDS.add( "public" ); - RESERVED_KEYWORDS.add( "throws" ); - RESERVED_KEYWORDS.add( "case" ); - RESERVED_KEYWORDS.add( "enum" ); - RESERVED_KEYWORDS.add( "instanceof" ); - RESERVED_KEYWORDS.add( "return" ); - RESERVED_KEYWORDS.add( "transient" ); - RESERVED_KEYWORDS.add( "catch" ); - RESERVED_KEYWORDS.add( "extends" ); - RESERVED_KEYWORDS.add( "int" ); - RESERVED_KEYWORDS.add( "short" ); - RESERVED_KEYWORDS.add( "try" ); - RESERVED_KEYWORDS.add( "char" ); - RESERVED_KEYWORDS.add( "final" ); - RESERVED_KEYWORDS.add( "interface" ); - RESERVED_KEYWORDS.add( "static" ); - RESERVED_KEYWORDS.add( "void" ); - RESERVED_KEYWORDS.add( "class" ); - RESERVED_KEYWORDS.add( "finally" ); - RESERVED_KEYWORDS.add( "long" ); - RESERVED_KEYWORDS.add( "strictfp" ); - RESERVED_KEYWORDS.add( "volatile" ); - RESERVED_KEYWORDS.add( "const" ); - RESERVED_KEYWORDS.add( "float" ); - RESERVED_KEYWORDS.add( "native" ); - RESERVED_KEYWORDS.add( "super" ); - RESERVED_KEYWORDS.add( "while" ); - } + private static final Set RESERVED_KEYWORDS; + static { + RESERVED_KEYWORDS = new HashSet<>(); - private NameConverter() {} - - /** - * Converts a database name (table or column) to a java name (first letter capitalised). - * employee_name -> EmployeeName. - *

- * Derived from middlegen's dbnameconverter. - * @param s The database name to convert. - * - * @return The converted database name. - */ - public static String toUpperCamelCase(String s) { - if (s.isEmpty()) { - return s; - } - StringBuilder result = new StringBuilder(); - - boolean capitalize = true; - boolean lastCapital = false; - boolean lastDecapitalized = false; - for (int i = 0; i < s.length(); i++) { - String c = s.substring(i, i + 1); - if ( "_".equals(c) || " ".equals(c) || "-".equals(c) ) { - capitalize = true; - continue; - } - - if ( c.toUpperCase().equals(c) ) { - if (lastDecapitalized && !lastCapital) { - capitalize = true; - } - lastCapital = true; - } - else { - lastCapital = false; - } - - //if(forceFirstLetter && result.length()==0) capitalize = false; - - if (capitalize) { + RESERVED_KEYWORDS.add( "abstract" ); + RESERVED_KEYWORDS.add( "continue" ); + RESERVED_KEYWORDS.add( "for" ); + RESERVED_KEYWORDS.add( "new" ); + RESERVED_KEYWORDS.add( "switch" ); + RESERVED_KEYWORDS.add( "assert" ); + RESERVED_KEYWORDS.add( "default" ); + RESERVED_KEYWORDS.add( "goto" ); + RESERVED_KEYWORDS.add( "package" ); + RESERVED_KEYWORDS.add( "synchronized" ); + RESERVED_KEYWORDS.add( "boolean" ); + RESERVED_KEYWORDS.add( "do" ); + RESERVED_KEYWORDS.add( "if" ); + RESERVED_KEYWORDS.add( "private" ); + RESERVED_KEYWORDS.add( "this" ); + RESERVED_KEYWORDS.add( "break" ); + RESERVED_KEYWORDS.add( "double" ); + RESERVED_KEYWORDS.add( "implements" ); + RESERVED_KEYWORDS.add( "protected" ); + RESERVED_KEYWORDS.add( "throw" ); + RESERVED_KEYWORDS.add( "byte" ); + RESERVED_KEYWORDS.add( "else" ); + RESERVED_KEYWORDS.add( "import" ); + RESERVED_KEYWORDS.add( "public" ); + RESERVED_KEYWORDS.add( "throws" ); + RESERVED_KEYWORDS.add( "case" ); + RESERVED_KEYWORDS.add( "enum" ); + RESERVED_KEYWORDS.add( "instanceof" ); + RESERVED_KEYWORDS.add( "return" ); + RESERVED_KEYWORDS.add( "transient" ); + RESERVED_KEYWORDS.add( "catch" ); + RESERVED_KEYWORDS.add( "extends" ); + RESERVED_KEYWORDS.add( "int" ); + RESERVED_KEYWORDS.add( "short" ); + RESERVED_KEYWORDS.add( "try" ); + RESERVED_KEYWORDS.add( "char" ); + RESERVED_KEYWORDS.add( "final" ); + RESERVED_KEYWORDS.add( "interface" ); + RESERVED_KEYWORDS.add( "static" ); + RESERVED_KEYWORDS.add( "void" ); + RESERVED_KEYWORDS.add( "class" ); + RESERVED_KEYWORDS.add( "finally" ); + RESERVED_KEYWORDS.add( "long" ); + RESERVED_KEYWORDS.add( "strictfp" ); + RESERVED_KEYWORDS.add( "volatile" ); + RESERVED_KEYWORDS.add( "const" ); + RESERVED_KEYWORDS.add( "float" ); + RESERVED_KEYWORDS.add( "native" ); + RESERVED_KEYWORDS.add( "super" ); + RESERVED_KEYWORDS.add( "while" ); + } + + private NameConverter() {} + + /** + * Converts a database name (table or column) to a java name (first letter capitalised). + * employee_name -> EmployeeName. + *

+ * Derived from middlegen's dbnameconverter. + * @param s The database name to convert. + * + * @return The converted database name. + */ + public static String toUpperCamelCase(String s) { + if (s.isEmpty()) { + return s; + } + StringBuilder result = new StringBuilder(); + + boolean capitalize = true; + boolean lastCapital = false; + boolean lastDecapitalized = false; + for (int i = 0; i < s.length(); i++) { + String c = s.substring(i, i + 1); + if ( "_".equals(c) || " ".equals(c) || "-".equals(c) ) { + capitalize = true; + continue; + } + + if ( c.toUpperCase().equals(c) ) { + if (lastDecapitalized && !lastCapital) { + capitalize = true; + } + lastCapital = true; + } + else { + lastCapital = false; + } + + //if(forceFirstLetter && result.length()==0) capitalize = false; + + if (capitalize) { result.append(c.toUpperCase()); capitalize = false; } - else { - result.append(c.toLowerCase() ); - lastDecapitalized = true; + else { + result.append(c.toLowerCase() ); + lastDecapitalized = true; } } return result.toString(); - } - - static public String simplePluralize(String singular) { - char last = singular.charAt( singular.length()-1 ); - Character prev = singular.length() > 1 ? singular.charAt( singular.length() - 2 ) : null; - String vowels = "aeiouy"; - switch (last) { - case 'x': - case 's': - singular += "es"; - break; - case 'y': - if (prev != null && vowels.indexOf(prev) >= 0){ - singular += "s"; - } else { - singular = singular.substring( 0, singular.length()-1 ) + "ies"; - } - break; - case 'h': - if (prev != null && (prev == 'c' || prev == 's')){ - singular += "es"; - break; - } - default: - singular += "s"; - } - return singular; - } + } + + static public String simplePluralize(String singular) { + char last = singular.charAt( singular.length()-1 ); + Character prev = singular.length() > 1 ? singular.charAt( singular.length() - 2 ) : null; + String vowels = "aeiouy"; + switch (last) { + case 'x': + case 's': + singular += "es"; + break; + case 'y': + if (prev != null && vowels.indexOf(prev) >= 0){ + singular += "s"; + } + else { + singular = singular.substring( 0, singular.length()-1 ) + "ies"; + } + break; + case 'h': + if (prev != null && (prev == 'c' || prev == 's')){ + singular += "es"; + break; + } + default: + singular += "s"; + } + return singular; + } - static public boolean isReservedJavaKeyword(String str) { - return RESERVED_KEYWORDS.contains(str); - } + static public boolean isReservedJavaKeyword(String str) { + return RESERVED_KEYWORDS.contains(str); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/util/SkipBackRefPropertyIterator.java b/orm/src/main/java/org/hibernate/tool/internal/util/SkipBackRefPropertyIterator.java index aa090fc9f2..56a76acb6a 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/util/SkipBackRefPropertyIterator.java +++ b/orm/src/main/java/org/hibernate/tool/internal/util/SkipBackRefPropertyIterator.java @@ -30,48 +30,49 @@ */ public class SkipBackRefPropertyIterator implements Iterator { - private Iterator delegate; + private final Iterator delegate; - private Property backLog; + private Property backLog; - public SkipBackRefPropertyIterator(Iterator iterator) { - delegate = iterator; - } + public SkipBackRefPropertyIterator(Iterator iterator) { + delegate = iterator; + } - public boolean hasNext() { - if ( backLog!=null ) { - return true; - } else if ( delegate.hasNext() ) { - Property nextProperty = (Property) delegate.next(); - while ( nextProperty.isBackRef() && delegate.hasNext() ) { - nextProperty = (Property) delegate.next(); - } - if ( !nextProperty.isBackRef() ) { - backLog = nextProperty; - return true; - } - } - return false; - } + public boolean hasNext() { + if ( backLog!=null ) { + return true; + } + else if ( delegate.hasNext() ) { + Property nextProperty = (Property) delegate.next(); + while ( nextProperty.isBackRef() && delegate.hasNext() ) { + nextProperty = (Property) delegate.next(); + } + if ( !nextProperty.isBackRef() ) { + backLog = nextProperty; + return true; + } + } + return false; + } - public Property next() { - if ( backLog != null ) { - Property p = backLog; - backLog = null; - return p; - } - Property nextProperty = (Property) delegate.next(); - while ( nextProperty.isBackRef() && delegate.hasNext() ) { - nextProperty = (Property) delegate.next(); - } - if ( nextProperty.isBackRef() ) { - throw new NoSuchElementException(); - } - return nextProperty; - } + public Property next() { + if ( backLog != null ) { + Property p = backLog; + backLog = null; + return p; + } + Property nextProperty = (Property) delegate.next(); + while ( nextProperty.isBackRef() && delegate.hasNext() ) { + nextProperty = (Property) delegate.next(); + } + if ( nextProperty.isBackRef() ) { + throw new NoSuchElementException(); + } + return nextProperty; + } - public void remove() { - throw new UnsupportedOperationException( "remove() not allowed" ); - } + public void remove() { + throw new UnsupportedOperationException( "remove() not allowed" ); + } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/xml/DOM3LSPrettyPrinterStrategy.java b/orm/src/main/java/org/hibernate/tool/internal/xml/DOM3LSPrettyPrinterStrategy.java index 87d22ba6c4..17c6cad0ba 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/xml/DOM3LSPrettyPrinterStrategy.java +++ b/orm/src/main/java/org/hibernate/tool/internal/xml/DOM3LSPrettyPrinterStrategy.java @@ -46,7 +46,8 @@ protected DOMImplementationLS getDomImplementationLS(final Document document) { final DOMImplementation domImplementation = document.getImplementation(); if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) { return (DOMImplementationLS) domImplementation.getFeature("LS", "3.0"); - } else { + } + else { throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported."); } } @@ -60,7 +61,8 @@ protected LSSerializer newLSSerializer(final DOMImplementationLS domImplementati lsSerializer.getDomConfig().setParameter("comments", isOutputComments()); } return lsSerializer; - } else { + } + else { throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable."); } } diff --git a/orm/src/main/java/org/hibernate/tool/internal/xml/XMLPrettyPrinterStrategyFactory.java b/orm/src/main/java/org/hibernate/tool/internal/xml/XMLPrettyPrinterStrategyFactory.java index 3ad9ff986b..5b5c84d4f2 100644 --- a/orm/src/main/java/org/hibernate/tool/internal/xml/XMLPrettyPrinterStrategyFactory.java +++ b/orm/src/main/java/org/hibernate/tool/internal/xml/XMLPrettyPrinterStrategyFactory.java @@ -41,9 +41,10 @@ private static XMLPrettyPrinterStrategy loadFromSystemProperty() { if (strategyClass != null) { try { Class clazz = (Class) Class.forName(strategyClass); - Constructor constructor = clazz.getConstructor(new Class[] {}); + Constructor constructor = clazz.getConstructor(); return constructor.newInstance(); - } catch (Exception e) { + } + catch (Exception e) { throw new RuntimeException(e); } }