List of usage examples for org.hibernate.mapping Column getName
public String getName()
From source file:com.amalto.core.storage.hibernate.mapping.MDMDenormalizedTable.java
License:Open Source License
@Override public Iterator sqlAlterStrings(Dialect dialect, Mapping p, TableMetadata tableInfo, String defaultCatalog, String defaultSchema) throws HibernateException { StringBuilder root = new StringBuilder("alter table ") .append(getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' '); Iterator iter = getColumnIterator(); List results = new ArrayList(); while (iter.hasNext()) { Column column = (Column) iter.next(); ColumnMetadata columnInfo = tableInfo.getColumnMetadata(column.getName()); if (columnInfo == null) { // the column doesnt exist at all. StringBuilder alter = new StringBuilder(root.toString()).append(dialect.getAddColumnString()) .append(' ').append(column.getQuotedName(dialect)).append(' ') .append(column.getSqlType(dialect, p)); String defaultValue = column.getDefaultValue(); if (defaultValue != null) { alter.append(" default ").append(defaultValue); }//from ww w . j a va2 s. c o m if (column.isNullable()) { alter.append(dialect.getNullColumnString()); } else { alter.append(" not null"); } if (column.isUnique()) { String keyName = Constraint.generateName("UK_", this, column); UniqueKey uk = getOrCreateUniqueKey(keyName); uk.addColumn(column); alter.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(column)); } if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) { alter.append(" check(").append(column.getCheckConstraint()).append(")"); } String columnComment = column.getComment(); if (columnComment != null) { alter.append(dialect.getColumnComment(columnComment)); } alter.append(dialect.getAddColumnSuffixString()); results.add(alter.toString()); } else if (MDMTableUtils.isAlterColumnField(column, columnInfo, dialect)) { StringBuilder alter = new StringBuilder(root.toString()); if (dialect instanceof SQLServerDialect || dialect instanceof PostgreSQLDialect) { alter.append(" ").append("alter COLUMN").append(" "); } else { alter.append(" ").append("modify").append(" "); } alter.append(" ").append(column.getQuotedName(dialect)).append(" "); if (dialect instanceof PostgreSQLDialect) { alter.append("TYPE").append(" "); } alter.append(column.getSqlType(dialect, p)); LOGGER.debug(alter.toString()); results.add(alter.toString()); } } return results.iterator(); }
From source file:com.amalto.core.storage.hibernate.mapping.MDMTable.java
License:Open Source License
@Override public Iterator sqlAlterStrings(Dialect dialect, Mapping p, TableMetadata tableInfo, String defaultCatalog, String defaultSchema) throws HibernateException { StringBuilder root = new StringBuilder("alter table ") .append(getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' '); Iterator iter = getColumnIterator(); List results = new ArrayList(); while (iter.hasNext()) { Column column = (Column) iter.next(); ColumnMetadata columnInfo = tableInfo.getColumnMetadata(column.getName()); if (columnInfo == null) { // the column doesnt exist at all. StringBuilder alter = new StringBuilder(root.toString()).append(dialect.getAddColumnString()) .append(' ').append(column.getQuotedName(dialect)).append(' ') .append(column.getSqlType(dialect, p)); String defaultValue = column.getDefaultValue(); if (defaultValue != null) { alter.append(" default ").append(defaultValue); }/* w w w .j a v a 2 s .c o m*/ if (column.isNullable()) { alter.append(dialect.getNullColumnString()); } else { alter.append(" not null"); } if (column.isUnique()) { String keyName = Constraint.generateName("UK_", this, column); UniqueKey uk = getOrCreateUniqueKey(keyName); uk.addColumn(column); alter.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(column)); } if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) { alter.append(" check(").append(column.getCheckConstraint()).append(")"); } String columnComment = column.getComment(); if (columnComment != null) { alter.append(dialect.getColumnComment(columnComment)); } alter.append(dialect.getAddColumnSuffixString()); results.add(alter.toString()); } else if (MDMTableUtils.isAlterColumnField(column, columnInfo, dialect)) { StringBuilder alter = new StringBuilder(root.toString()); if (dialect instanceof SQLServerDialect || dialect instanceof PostgreSQLDialect) { alter.append(" ").append("alter COLUMN").append(" "); } else { alter.append(" ").append("modify").append(" "); } alter.append(" ").append(column.getQuotedName(dialect)).append(" "); if (dialect instanceof PostgreSQLDialect) { alter.append("TYPE").append(" "); } alter.append(column.getSqlType(dialect, p)); String defaultValue = column.getDefaultValue(); if (defaultValue != null) { alter.append(" default ").append(defaultValue); } if (column.isNullable()) { alter.append(dialect.getNullColumnString()); } else { alter.append(" not null"); } if (column.isUnique()) { String keyName = Constraint.generateName("UK_", this, column); UniqueKey uk = getOrCreateUniqueKey(keyName); uk.addColumn(column); alter.append(dialect.getUniqueDelegate().getColumnDefinitionUniquenessFragment(column)); } if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) { alter.append(" check(").append(column.getCheckConstraint()).append(")"); } String columnComment = column.getComment(); if (columnComment != null) { alter.append(dialect.getColumnComment(columnComment)); } alter.append(dialect.getAddColumnSuffixString()); LOGGER.debug(alter.toString()); results.add(alter.toString()); } } return results.iterator(); }
From source file:com.clican.pluto.orm.dynamic.impl.DataBaseOperationImpl.java
License:LGPL
@SuppressWarnings("unchecked") public void alterTable(Configuration cfg, ModelDescription oldOne, ModelDescription newOne) { Connection conn = null;/* w w w. ja v a2s . c o m*/ DatabaseMetadata meta = null; String defaultCatalog = cfg.getProperties().getProperty(Environment.DEFAULT_CATALOG); String defaultSchema = cfg.getProperties().getProperty(Environment.DEFAULT_SCHEMA); List<String> alterSqls = new ArrayList<String>(); try { conn = dataSource.getConnection(); meta = new DatabaseMetadata(conn, dialect); Mapping mapping = cfg.buildMapping(); // Alter table name; if (!oldOne.getName().equals(newOne.getName())) { String alterTableName = "alter table " + dialect.openQuote() + oldOne.getName().toUpperCase() + dialect.closeQuote() + "rename to " + dialect.openQuote() + newOne.getName().toUpperCase() + dialect.closeQuote(); executeSql(conn, alterTableName); } List<PropertyDescription> oldPropertyDescriptionList = oldOne.getPropertyDescriptionList(); List<PropertyDescription> currentPropertyDescriptionList = newOne.getPropertyDescriptionList(); List<PropertyDescription> removePropertyList = new ArrayList<PropertyDescription>(); List<PropertyDescription> addPropertyList = new ArrayList<PropertyDescription>( currentPropertyDescriptionList); Map<PropertyDescription, PropertyDescription> pdMap = new HashMap<PropertyDescription, PropertyDescription>(); for (PropertyDescription pd1 : oldPropertyDescriptionList) { boolean remove = true; for (PropertyDescription pd2 : currentPropertyDescriptionList) { if (pd1.getId().equals(pd2.getId())) { addPropertyList.remove(pd2); if (!pd1.equals(pd2)) { pdMap.put(pd2, pd1); } remove = false; break; } } if (remove) { removePropertyList.add(pd1); } } Iterator<Table> tableIter = cfg.getTableMappings(); while (tableIter.hasNext()) { Table table = tableIter.next(); TableMetadata tableInfo = meta.getTableMetadata(table.getName(), (table.getSchema() == null) ? defaultSchema : table.getSchema(), (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted() ); if (tableInfo == null) { alterSqls.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema)); } else { if (!table.getName().equalsIgnoreCase(newOne.getName())) { continue; } for (PropertyDescription removeProperty : removePropertyList) { if (removeProperty.getControl().isSupportMutil() && removeProperty.getControl().isDynamic()) { alterSqls.add("drop table " + dialect.openQuote() + newOne.getName().toUpperCase() + "_" + removeProperty.getName().toUpperCase() + "_RELATION" + dialect.closeQuote()); } else { if (((DialectExtention) dialect).needDropForeignKeyBeforeDropColumn()) { ForeignKeyMetadata fkm = tableInfo.getForeignKeyMetadataByColumnNames( new String[] { removeProperty.getName().toUpperCase() }); if (fkm != null) { alterSqls.add("alter table " + dialect.openQuote() + newOne.getName().toUpperCase() + dialect.closeQuote() + " " + dialect.getDropForeignKeyString() + " " + dialect.openQuote() + fkm.getName() + dialect.closeQuote()); } } alterSqls.add("alter table " + dialect.openQuote() + newOne.getName().toUpperCase() + dialect.closeQuote() + " drop column " + dialect.openQuote() + removeProperty.getName().toUpperCase() + dialect.closeQuote()); } } StringBuffer root = new StringBuffer("alter table ") .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ') .append(dialect.getAddColumnString()); Iterator<Column> iter = table.getColumnIterator(); while (iter.hasNext()) { Column column = iter.next(); PropertyDescription pd = null; if ((pd = contains(column.getName(), addPropertyList)) != null) { StringBuffer alter = new StringBuffer(root.toString()).append(' ') .append(column.getQuotedName(dialect)).append(' ') .append(column.getSqlType(dialect, mapping)); String defaultValue = column.getDefaultValue(); if (defaultValue != null) { alter.append(" default ").append(defaultValue); if (column.isNullable()) { alter.append(dialect.getNullColumnString()); } else { alter.append(" not null"); } } boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique() && (!column.isNullable() || dialect.supportsNotNullUnique()); if (useUniqueConstraint) { alter.append(" unique"); } if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) { alter.append(" check(").append(column.getCheckConstraint()).append(")"); } String columnComment = column.getComment(); if (columnComment != null) { alter.append(dialect.getColumnComment(columnComment)); } alterSqls.add(alter.toString()); } else if ((pd = contains(column.getName(), pdMap)) != null) { PropertyDescription newPd = pd; PropertyDescription oldPd = pdMap.get(pd); if (!oldPd.getName().equalsIgnoreCase(newPd.getName())) { StringBuffer renameColumn = new StringBuffer("alter table ") .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)) .append(' ').append(((DialectExtention) dialect).getRenameColumnString( oldPd.getName().toUpperCase(), newPd.getName().toUpperCase())); if (((DialectExtention) dialect).isAddColumnDefinitionWhenRename()) { renameColumn.append(" "); renameColumn.append(column.getSqlType(dialect, mapping)); } executeSql(conn, renameColumn.toString()); } StringBuffer alterColumn = new StringBuffer("alter table ") .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)) .append(' ').append(((DialectExtention) dialect).getModifyColumnString(column)) .append(' ').append(column.getQuotedName(dialect)); alterColumn.append(" "); alterColumn.append(column.getSqlType(dialect, mapping)); String defaultValue = column.getDefaultValue(); if (defaultValue != null) { alterColumn.append(" default ").append(defaultValue); if (column.isNullable()) { alterColumn.append(dialect.getNullColumnString()); } else { alterColumn.append(" not null"); } } boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique() && (!column.isNullable() || dialect.supportsNotNullUnique()); if (useUniqueConstraint) { alterColumn.append(" unique"); } if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) { alterColumn.append(" check(").append(column.getCheckConstraint()).append(")"); } String columnComment = column.getComment(); if (columnComment != null) { alterColumn.append(dialect.getColumnComment(columnComment)); } alterSqls.add(alterColumn.toString()); } } } } tableIter = cfg.getTableMappings(); while (tableIter.hasNext()) { Table table = tableIter.next(); Iterator<ForeignKey> subIter = table.getForeignKeyIterator(); while (subIter.hasNext()) { ForeignKey fk = (ForeignKey) subIter.next(); if (fk.isPhysicalConstraint()) { TableMetadata tableInfo = meta.getTableMetadata(table.getName(), (table.getSchema() == null) ? defaultSchema : table.getSchema(), (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted() ); if (tableInfo == null) { String[] cols = new String[fk.getColumnSpan()]; String[] refcols = new String[fk.getColumnSpan()]; int i = 0; Iterator<Column> refiter = null; if (fk.isReferenceToPrimaryKey()) { refiter = fk.getReferencedTable().getPrimaryKey().getColumnIterator(); } else { refiter = fk.getReferencedColumns().iterator(); } Iterator<Column> columnIter = fk.getColumnIterator(); while (columnIter.hasNext()) { cols[i] = ((Column) columnIter.next()).getQuotedName(dialect); refcols[i] = ((Column) refiter.next()).getQuotedName(dialect); i++; } String result = dialect .getAddForeignKeyConstraintString( fk.getName(), cols, fk.getReferencedTable().getQualifiedName(dialect, defaultCatalog, defaultSchema), refcols, fk.isReferenceToPrimaryKey()); StringBuffer createFK = new StringBuffer("alter table ") .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)) .append(dialect.supportsCascadeDelete() ? result + " on delete cascade" : result); alterSqls.add(createFK.toString()); } } } } this.executeSqls(conn, alterSqls); } catch (Exception e) { throw new PlutoException(e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { log.error("", e); } } } }
From source file:com.clueride.rest.MemberWebService.java
License:Apache License
private void dumpEntities() { Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata(); for (PersistentClass persistentClass : metadata.getEntityBindings()) { Table table = persistentClass.getTable(); LOGGER.info(String.format("Entity: {} is mapped to table: {}", persistentClass.getClassName(), table.getName()));/*ww w . j ava 2 s . c o m*/ for (Iterator propertyIterator = persistentClass.getPropertyIterator(); propertyIterator.hasNext();) { Property property = (Property) propertyIterator.next(); for (Iterator columnIterator = property.getColumnIterator(); columnIterator.hasNext();) { Column column = (Column) columnIterator.next(); LOGGER.info(String.format("Property: {} is mapped on table column: {} of type: {}", property.getName(), column.getName(), column.getSqlType())); } } } }
From source file:com.fiveamsolutions.nci.commons.audit.AuditLogInterceptor.java
License:Open Source License
/** * Retrieves the column name for the given PersistentClass and fieldName. * * @param pc//from ww w. j a v a 2 s .c o m * @param fieldName * @return columnName */ private static String getColumnName(PersistentClass pc, String fieldName) { if (pc == null) { return null; } String columnName = null; Property property = pc.getProperty(fieldName); for (Iterator<?> it3 = property.getColumnIterator(); it3.hasNext();) { Object o = it3.next(); if (!(o instanceof Column)) { LOG.debug("Skipping non-column (probably a formula"); continue; } Column column = (Column) o; columnName = column.getName(); break; } if (columnName == null) { try { columnName = getColumnName(pc.getSuperclass(), fieldName); } catch (MappingException e) { // in this case the annotation / mapping info was at the current class and not the base class // but for some reason the column name could not be determined. // This will happen when a subclass of an entity uses a joined subclass. // in this case just set column Name to null and let the caller default to the property name. columnName = null; } } return columnName; }
From source file:com.github.gekoh.yagen.api.DefaultNamingStrategy.java
License:Apache License
@Override public String constraintName(Constraint constraint, String entityClass) { String name = constraint.getName(); if (constraint instanceof ForeignKey || constraint instanceof UniqueKey) { StringBuilder colList = new StringBuilder(); for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint .getColumns()) {/* w w w. ja v a2 s.c o m*/ if (colList.length() > 0) { colList.append(", "); } colList.append(column.getName().toLowerCase()); } name = beautifyConstraintName(name, entityClass, tableName(constraint.getTable().getName()), concatColumnNames(colList.toString())); } return constraintName(name); }
From source file:com.github.gekoh.yagen.ddl.CreateDDL.java
License:Apache License
public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table, Constraint constraint) {/*from w w w . java 2 s . c o m*/ NamingStrategy namingStrategy = getProfile().getNamingStrategy(); String newName = namingStrategy.constraintName(constraint, getEntityClassName(namingStrategy.tableName(table.getName()))); if (!name.equals(newName)) { String sqlCreate = buf.toString(); Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate); if (matcher.find()) { buf = new StringBuffer(); buf.append(sqlCreate.substring(0, matcher.start(1))); buf.append(newName); buf.append(sqlCreate.substring(matcher.end(1))); } name = newName; } String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase(); if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) { return "-- skipped creation of constraint '" + name + "' for table '" + table.getName() + "' as the mapped entity was not chosen to be processed or is a view"; } TableConfig tableConfig = tblNameToConfig.get(tableNameLC); String refTblNameLC = null; if (constraint instanceof ForeignKey) { if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) { return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName() + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName(); } refTblNameLC = getProfile().getNamingStrategy() .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase(); } checkObjectName(dialect, name); String i18nFK = tableConfig.getI18nBaseEntityFkCol(); if (i18nFK != null) { StringBuilder sql = new StringBuilder(); tableNameLC = getI18NDetailTableName(tableNameLC); Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString()); if (matcher.find()) { sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC) .append(buf.substring(matcher.end(1))); } buf = new StringBuffer(sql.toString()); } if (constraint instanceof ForeignKey) { StringBuilder colList = new StringBuilder(); org.hibernate.mapping.Column singleColumn = null; TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC); IntervalPartitioning refTblPart = refTableConfig != null ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class) : null; for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint .getColumns()) { if (colList.length() > 0) { colList.append(", "); } colList.append(column.getName().toLowerCase()); singleColumn = singleColumn == null ? column : null; } if (externalViews.contains(refTblNameLC)) { buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC + "' since a view will be referenced"); } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) { buf = new StringBuffer(); buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '") .append(tableNameLC).append("' to table '").append(refTblNameLC) .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ") .append(((ForeignKey) constraint).getReferencedEntityName()).append(")"); } else { if (singleColumn != null) { if (tableConfig.getColumnNamesIsCascadeNullable() .contains(singleColumn.getName().toLowerCase())) { buf.append(" on delete set null"); } else if (tableConfig.getColumnNamesIsCascadeDelete() .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) { buf.append(" on delete cascade"); } } Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable(); Deferrable deferrable; if (supportsDeferrable(dialect) && col2Deferrable != null && (deferrable = col2Deferrable.get(colList.toString())) != null) { buf.append(" deferrable"); if (deferrable.initiallyDeferred()) { buf.append(" initially deferred"); } } if (getProfile().isDisableFKs()) { buf.insert(0, "-- creating FK constraint initially disabled since we do not need it for profile '" + getProfile() + "'\n"); buf.append(" disable"); } } getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString()); if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) { LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC + " and column " + colList.toString()); } else { String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC), tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString())); StringBuilder objDdl = new StringBuilder(); objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (") .append(colList.toString()).append(")"); if (constraint.getColumnSpan() == 1) { tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString()); } buf.append(STATEMENT_SEPARATOR).append(objDdl); getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString()); } } return buf.toString(); }
From source file:com.github.gekoh.yagen.ddl.CreateDDL.java
License:Apache License
private boolean hasIndex(Table table, String tableNameLC, org.hibernate.mapping.Column column) { String columnName = column.getName().toLowerCase(); if (tblColNameHasSingleColIndex.contains(tableNameLC + "." + columnName)) { return true; }//ww w . ja v a 2 s . c o m TableConfig tableConfig = tblNameToConfig.get(tableNameLC); List<String> pkCols = tableConfig != null ? tableConfig.getPkColnames() : null; if (pkCols != null && pkCols.size() == 1 && pkCols.contains(columnName)) { return true; } PrimaryKey pk = table.getPrimaryKey(); if (pk != null && pk.getColumnSpan() == 1 && pk.getColumns().get(0).equals(column)) { return true; } Iterator<UniqueKey> uniqueKeyIterator = table.getUniqueKeyIterator(); while (uniqueKeyIterator.hasNext()) { UniqueKey uk = uniqueKeyIterator.next(); if (uk.getColumnSpan() == 1 && uk.containsColumn(column)) { return true; } } return column.isUnique(); }
From source file:com.github.gekoh.yagen.hibernate.PatchGlue.java
License:Apache License
public static String afterTableSqlCreateString(Table table, Dialect dialect, String returnValue) { StringBuffer buf = new StringBuffer(returnValue); Map<String, Column> allColumns = new LinkedHashMap<String, Column>(); Iterator<Column> colIt = table.getColumnIterator(); while (colIt.hasNext()) { Column column = colIt.next(); allColumns.put(column.getName().toLowerCase(), column); }/*from w w w.j ava2 s.c o m*/ CreateDDL ddlEnhancer = getDDLEnhancerFromDialect(dialect); if (ddlEnhancer == null) { return returnValue; } return ddlEnhancer.updateCreateTable(dialect, buf.append(dialect.getTableTypeString()), table.getName(), allColumns); }
From source file:com.github.shyiko.rook.target.hibernate4.fulltextindex.PrimaryKey.java
License:Apache License
private Map<String, Integer> getColumnIndexByNameMap(Table table) { Map<String, Integer> columnIndexByName = new HashMap<String, Integer>(); int index = 0; Iterator columnIterator = table.getColumnIterator(); while (columnIterator.hasNext()) { Column column = (Column) columnIterator.next(); columnIndexByName.put(column.getName(), index++); }//from w w w . j a v a 2 s . c o m return columnIndexByName; }