List of usage examples for org.hibernate.mapping Table getColumnIterator
public Iterator getColumnIterator()
From source file:com.blazebit.persistence.integration.hibernate.base.SimpleDatabase.java
License:Apache License
public SimpleDatabase(Iterator<Table> iter, Dialect dialect, TableNameFormatter formatter, Mapping mapping) { Map<String, Table> map = new HashMap<String, Table>(); while (iter.hasNext()) { Table t = iter.next(); map.put(formatter.getQualifiedTableName(dialect, t), t); if (t.getSubselect() != null) { map.put("( " + t.getSubselect() + " )", t); }//w w w .java 2 s .c o m Iterator<Column> columnIter = t.getColumnIterator(); while (columnIter.hasNext()) { final Column column = columnIter.next(); column.getSqlType(dialect, mapping); } } this.tables = Collections.unmodifiableMap(map); }
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;/*from w w w. ja v a2 s .com*/ 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.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();// w w w . j a v a 2s . co m allColumns.put(column.getName().toLowerCase(), column); } 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 ww . j a v a 2s.co m return columnIndexByName; }
From source file:com.github.shyiko.rook.target.hibernate4.fulltextindex.SynchronizationContext.java
License:Apache License
@SuppressWarnings("unchecked") private PrimaryKey resolveForeignPrimaryKey(org.hibernate.mapping.Collection collection, Map<String, IndexingDirective> directivesByEntityNameMap) { Table collectionTable = collection.getCollectionTable(); ToOne element = (ToOne) collection.getElement(); IndexingDirective indexingDirective = directivesByEntityNameMap.get(element.getReferencedEntityName()); if (indexingDirective == null) { return null; }//from w w w .java 2 s .c o m Collection<String> targetPrimaryKeyColumnNames = new HashSet<String>(); for (Iterator<Column> columnIterator = element.getColumnIterator(); columnIterator.hasNext();) { Column column = columnIterator.next(); targetPrimaryKeyColumnNames.add(column.getName()); } Map<String, Integer> columnIndexByNameMap = new HashMap<String, Integer>(); int index = 0; for (Iterator<Column> columnIterator = collectionTable.getColumnIterator(); columnIterator.hasNext();) { Column column = columnIterator.next(); if (targetPrimaryKeyColumnNames.contains(column.getName())) { columnIndexByNameMap.put(column.getName(), index); } index++; } return new PrimaryKey(indexingDirective.getPrimaryKey(), columnIndexByNameMap); }
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
private DependantValue createFKComposite(Mappings mappings, com.manydesigns.portofino.model.database.ForeignKey relationship, com.manydesigns.portofino.model.database.Table manyMDTable, PersistentClass clazzOne, PersistentClass clazzMany, Bag set, Table tableMany, Table tableOne, List<Column> oneColumns, List<Column> manyColumns) { DependantValue dv;/*from ww w.ja va2s . c om*/ Component component = new Component(mappings, set); component.setDynamic(manyMDTable.getActualJavaClass() == null); component.setEmbedded(true); dv = new DependantValue(mappings, clazzMany.getTable(), component); dv.setNullable(true); dv.setUpdateable(true); for (Reference ref : relationship.getReferences()) { String colToName = ref.getToColumn(); String colToPropertyName = ref.getActualToColumn().getActualPropertyName(); String colFromName = ref.getFromColumn(); Iterator it = tableMany.getColumnIterator(); while (it.hasNext()) { Column col = (Column) it.next(); if (col.getName().equals(colFromName)) { dv.addColumn(col); manyColumns.add(col); break; } } Iterator it2 = tableOne.getColumnIterator(); while (it2.hasNext()) { Column col = (Column) it2.next(); if (col.getName().equals(colToName)) { oneColumns.add(col); break; } } Property refProp; refProp = getRefProperty(clazzOne, colToPropertyName); component.addProperty(refProp); } return dv; }
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
private DependantValue createFKSingle(Mappings mappings, PersistentClass clazzOne, PersistentClass clazzMany, Table tableOne, List<Column> oneColumns, List<Column> manyColumns, List<Reference> refs) { DependantValue dv;//from ww w . ja va2 s . c o m Property refProp; Reference reference = refs.get(0); String colFromName = reference.getFromColumn(); String colToName = reference.getToColumn(); String colToPropertyName = reference.getActualToColumn().getActualPropertyName(); refProp = getRefProperty(clazzOne, colToPropertyName); dv = new DependantValue(mappings, clazzMany.getTable(), refProp.getPersistentClass().getKey()); dv.setNullable(true); dv.setUpdateable(true); Iterator it = clazzMany.getTable().getColumnIterator(); while (it.hasNext()) { Column col = (Column) it.next(); if (col.getName().equals(colFromName)) { dv.addColumn(col); manyColumns.add(col); break; } } Iterator it2 = tableOne.getColumnIterator(); while (it2.hasNext()) { Column col = (Column) it2.next(); if (col.getName().equals(colToName)) { oneColumns.add(col); break; } } return dv; }
From source file:com.netspective.tool.hibernate.document.diagram.HibernateDiagramTableStructureNodeGenerator.java
License:Open Source License
public GraphvizDiagramNode generateTableNode(final HibernateDiagramGenerator generator, final HibernateDiagramGeneratorFilter filter, final PersistentClass pclass) { final Table table = pclass.getTable(); final StringBuffer primaryKeyRows = new StringBuffer(); final StringBuffer childKeyRows = new StringBuffer(); final StringBuffer columnRows = new StringBuffer(); final PrimaryKey primaryKeyColumns = table.getPrimaryKey(); final String indent = " "; int hidden = 0; for (final Iterator columns = table.getColumnIterator(); columns.hasNext();) { final Column column = (Column) columns.next(); if (filter.includeColumnInDiagram(generator, column)) { try { ForeignKey partOfForeignKey = null; for (Iterator fkIterator = table.getForeignKeyIterator(); fkIterator.hasNext();) { final ForeignKey fKey = (ForeignKey) fkIterator.next(); if (fKey.containsColumn(column)) { partOfForeignKey = fKey; break; }/*from w w w .j a va2s.co m*/ } if (primaryKeyColumns.containsColumn(column)) primaryKeyRows.append(filter.getColumnDefinitionHtml(generator, column, primaryKeyColumns, partOfForeignKey, showDataTypes, showConstraints, indent) + "\n"); else if (partOfForeignKey != null && generator.isParentRelationship(partOfForeignKey)) childKeyRows.append(filter.getColumnDefinitionHtml(generator, column, null, partOfForeignKey, showDataTypes, showConstraints, indent) + "\n"); else columnRows.append(filter.getColumnDefinitionHtml(generator, column, null, partOfForeignKey, showDataTypes, showConstraints, indent) + "\n"); } catch (SQLException e) { throw new HibernateDiagramGeneratorException(e); } catch (NamingException e) { throw new HibernateDiagramGeneratorException(e); } } else hidden++; } int colSpan = 1; if (showDataTypes) colSpan++; if (showConstraints) colSpan++; StringBuffer tableNodeLabel = new StringBuffer( "<<TABLE " + filter.getEntityTableHtmlAttributes(generator, pclass) + ">\n"); tableNodeLabel.append(" <TR><TD COLSPAN=\"" + colSpan + "\" " + filter.getTableNameCellHtmlAttributes(generator, pclass) + ">" + table.getName() + "</TD></TR>\n"); if (primaryKeyRows.length() > 0) tableNodeLabel.append(primaryKeyRows); if (childKeyRows.length() > 0) tableNodeLabel.append(childKeyRows); tableNodeLabel.append(columnRows); if (hidden > 0) tableNodeLabel.append( " <TR><TD COLSPAN=\"" + colSpan + "\">(" + hidden + " columns not shown)</TD></TR>\n"); tableNodeLabel.append(" </TABLE>>"); GraphvizDiagramNode result = new GraphvizDiagramNode(generator.getGraphvizDiagramGenerator(), table.getName()); result.setLabel(tableNodeLabel.toString()); result.setShape("plaintext"); result.setFontName("Helvetica"); return result; }
From source file:com.tomitribe.reveng.codegen.FreemarkerObject.java
License:Apache License
public String annotate(final BasicPOJOClass pojo, final Object pObj, final Object rootObj, final Object toolObj) { // public String annotate(final Object pojo, final Property p, final // RootClass root, final Cfg2HbmTool tool) { if (BasicPOJOClass.class.isInstance(pojo)) { } else {/*from w w w . j a v a 2 s. c om*/ // System.out.println(ob.class.getName()); } RootClass root = null; try { root = (RootClass) rootObj; } catch (final Exception e) { // TODO Auto-generated catch block // e.printStackTrace(); return ""; } final Property p = (Property) pObj; final Cfg2HbmTool tool = (Cfg2HbmTool) toolObj; final Table table = root.getTable(); Iterator it = table.getColumnIterator(); Column column = null; Column c; String name; while (it.hasNext()) { c = (Column) it.next(); name = c.getName().replace("_", "").toLowerCase(); if (name.equals(p.getName().toLowerCase())) { column = c; break; } } if (null != column) { System.out.print("FreemarkerObject.annotate: " + table.getName() + " - " + p.getName() + " - "); it = table.getIndexIterator(); org.hibernate.mapping.Index index; while (it.hasNext()) { final Object next = it.next(); if (org.hibernate.mapping.Index.class.isInstance(next)) { index = org.hibernate.mapping.Index.class.cast(next); if (index.containsColumn(column)) { System.out.print(index.getName()); return String.format("\n@Index(name = \"%1$s\", columnNames = {\"%2$s\"})", index.getName().toLowerCase(), column.getName()); } } } System.out.println(); } else { System.out.println("FreemarkerObject.annotate: " + table.getName() + " - " + p.getName() + " - " + p.getNodeName() + " - " + p.getPropertyAccessorName()); } return ""; }
From source file:com.vecna.dbDiff.hibernate.HibernateMappingsConverter.java
License:Apache License
/** * Convert a Hibernate table model to the DbDiff table model. * @param mappedTable hibernate table./*from ww w . j a v a2 s . c o m*/ * @return DbDiff table. */ private RelationalTable convertTable(org.hibernate.mapping.Table mappedTable) { RelationalTable table = new RelationalTable(m_catalogSchema, getTableName(mappedTable)); List<Column> columns = new ArrayList<>(); List<RelationalIndex> indices = new ArrayList<>(); @SuppressWarnings("unchecked") Iterator<org.hibernate.mapping.Column> mappedColumns = mappedTable.getColumnIterator(); int idx = 1; while (mappedColumns.hasNext()) { org.hibernate.mapping.Column mappedColumn = mappedColumns.next(); Column column = convertColumn(mappedColumn, mappedTable, idx++); columns.add(column); if (mappedColumn.isUnique()) { indices.add(getUniqueIndex(table, column)); } } table.setColumns(columns); Set<ForeignKey> fkeys = new HashSet<>(); @SuppressWarnings("unchecked") Iterator<org.hibernate.mapping.ForeignKey> mappedKeys = mappedTable.getForeignKeyIterator(); while (mappedKeys.hasNext()) { convertForeignKey(mappedKeys.next(), fkeys); } table.setFks(fkeys); @SuppressWarnings("unchecked") Iterator<Index> mappedIndices = mappedTable.getIndexIterator(); while (mappedIndices.hasNext()) { indices.add(convertIndex(mappedIndices.next(), table)); } @SuppressWarnings("unchecked") Iterator<UniqueKey> mappedUniqueKeys = mappedTable.getUniqueKeyIterator(); while (mappedUniqueKeys.hasNext()) { indices.add(convertIndex(mappedUniqueKeys.next(), table)); } if (mappedTable.getPrimaryKey() != null) { indices.add(convertIndex(mappedTable.getPrimaryKey(), table)); List<String> pkColumnNames = new ArrayList<>(); @SuppressWarnings("unchecked") Iterator<org.hibernate.mapping.Column> pkColumns = mappedTable.getPrimaryKey().getColumnIterator(); while (pkColumns.hasNext()) { pkColumnNames.add(getColumnName(pkColumns.next())); } table.setPkColumns(pkColumnNames); } table.setIndices(indices); return table; }