List of usage examples for org.hibernate.mapping Table getPrimaryKey
public PrimaryKey getPrimaryKey()
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; }//from w w w. j a v a2 s.c om 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.krawler.esp.hibernate.impl.HibernateUtil.java
License:Open Source License
public static String getPrimaryColName(Table table) throws ServiceException { String colName = ""; try {/* w w w .ja v a2 s .com*/ PrimaryKey pk = table.getPrimaryKey(); List lst = pk.getColumns(); Column col = (Column) lst.get(0); colName = col.getName(); } catch (Exception e) { throw ServiceException.FAILURE("HibernateUtil.getPrimaryColName", e); } return colName; }
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
private Mappings classMapping(Database database, Mappings mappings) { for (Schema schema : database.getSchemas()) { for (com.manydesigns.portofino.model.database.Table aTable : schema.getTables()) { logger.debug("Class - {}", aTable.getQualifiedName()); com.manydesigns.portofino.model.database.PrimaryKey primaryKey = aTable.getPrimaryKey(); if (primaryKey == null) { logger.debug("Skipping table without primary key: {}", aTable.getQualifiedName()); continue; }//w ww. j av a 2s . c o m if (!primaryKey.isValid()) { logger.debug("Skipping table with invalid primary key: {}", aTable.getQualifiedName()); continue; } RootClass clazz = createTableMapping(mappings, aTable); if (clazz != null) { mappings.addClass(clazz); mappings.addImport(clazz.getEntityName(), clazz.getEntityName()); } } } return mappings; }
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
protected RootClass createTableMapping(Mappings mappings, com.manydesigns.portofino.model.database.Table aTable) { Table tab = mappings.addTable(escapeName(aTable.getSchemaName()), null, escapeName(aTable.getTableName()), null, false);/*from w w w . ja va 2 s . c o m*/ //tab.setName(escapeName(aTable.getTableName())); //tab.setSchema(escapeName(aTable.getSchemaName())); mappings.addTableBinding(aTable.getSchemaName(), null, aTable.getTableName(), aTable.getTableName(), null); RootClass clazz = new RootClass(); clazz.setEntityName(aTable.getActualEntityName()); clazz.setJpaEntityName(aTable.getActualEntityName()); if (aTable.getJavaClass() != null) { clazz.setClassName(aTable.getJavaClass()); clazz.setProxyInterfaceName(aTable.getJavaClass()); } clazz.setLazy(LAZY); clazz.setTable(tab); //clazz.setNodeName(aTable.getTableName()); List<com.manydesigns.portofino.model.database.Column> columnList = new ArrayList<com.manydesigns.portofino.model.database.Column>(); for (com.manydesigns.portofino.model.database.Column modelColumn : aTable.getColumns()) { int jdbcType = modelColumn.getJdbcType(); Class javaType = modelColumn.getActualJavaType(); //First param = null ==> doesn't really set anything, just check boolean hibernateTypeOk = setHibernateType(null, modelColumn, javaType, jdbcType); if (hibernateTypeOk) { columnList.add(modelColumn); } else { logger.error( "Cannot find Hibernate type for table: {}, column: {}, jdbc type: {}, type name: {}. Skipping column.", new Object[] { aTable.getQualifiedName(), modelColumn.getColumnName(), jdbcType, javaType != null ? javaType.getName() : null }); } } //Primary keys List<com.manydesigns.portofino.model.database.Column> columnPKList = aTable.getPrimaryKey().getColumns(); if (!columnList.containsAll(columnPKList)) { logger.error("Primary key refers to some invalid columns, skipping table {}", aTable.getQualifiedName()); return null; } if (columnPKList.size() > 1) { createPKComposite(mappings, aTable, aTable.getPrimaryKey().getPrimaryKeyName(), clazz, tab, columnPKList); } else { createPKSingle(mappings, aTable, aTable.getPrimaryKey().getPrimaryKeyName(), clazz, tab, columnPKList); } //Other columns columnList.removeAll(columnPKList); for (com.manydesigns.portofino.model.database.Column column : columnList) { Column col = createColumn(mappings, tab, column); if (col != null) { clazz.addProperty(createProperty(column, col.getValue())); } } return clazz; }
From source file:com.manydesigns.portofino.persistence.hibernate.HibernateConfig.java
License:Open Source License
protected void createPKSingle(Mappings mappings, com.manydesigns.portofino.model.database.Table mdTable, String pkName, RootClass clazz, Table tab, List<com.manydesigns.portofino.model.database.Column> columnPKList) { PrimaryKeyColumn pkcol = mdTable.getPrimaryKey().getPrimaryKeyColumns().get(0); com.manydesigns.portofino.model.database.Column column = columnPKList.get(0); final PrimaryKey primaryKey = new PrimaryKey(); primaryKey.setName(pkName);//ww w . j a v a 2 s . c om primaryKey.setTable(tab); tab.setPrimaryKey(primaryKey); Column col = createColumn(mappings, tab, column); if (col == null) { // TODO PAOLO: se la PK non e' buona, tutta la tabella dovrebbe saltare logger.error("Skipping primary key"); return; } SimpleValue id = (SimpleValue) col.getValue(); //Make the defaults explicit. See section 5.1.4.5. Assigned identifiers in the Hibernate reference //(http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html) id.setIdentifierGeneratorStrategy("assigned"); id.setNullValue("undefined"); tab.getPrimaryKey().addColumn(col); Property prop = createProperty(column, id); clazz.addProperty(prop); prop.setPropertyAccessorName(mappings.getDefaultAccess()); //PropertyGeneration generation = PropertyGeneration.parse(null); //prop.setGeneration(generation); prop.setInsertable(false); prop.setUpdateable(false); Generator generator = pkcol.getGenerator(); setPKColumnGenerator(mappings, clazz, tab, column, id, generator); tab.setIdentifierValue(id); clazz.setIdentifier(id); clazz.setIdentifierProperty(prop); clazz.setDiscriminatorValue(mdTable.getQualifiedName()); }
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 .jav a 2 s. c o 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.vecna.dbDiff.hibernate.HibernateMappingsConverter.java
License:Apache License
/** * Convert a Hibernate table model to the DbDiff table model. * @param mappedTable hibernate table./*www .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; }
From source file:com.vecna.dbDiff.hibernate.HibernateMappingsConverter.java
License:Apache License
/** * Convert a Hibernate foreign key object to a {@link ForeignKey} * @param mappedKey hibernate foreign key. * @param columnIndex 0-based index of the column in a foreign key. * @return a {@link ForeignKey} representation of the same foreign key. *//*ww w . j av a 2 s. c o m*/ private ForeignKey convertForeignKey(org.hibernate.mapping.ForeignKey mappedKey, int columnIndex) { org.hibernate.mapping.Column column = mappedKey.getColumn(columnIndex); org.hibernate.mapping.Table table = mappedKey.getTable(); org.hibernate.mapping.Table referencedTable = mappedKey.getReferencedTable(); org.hibernate.mapping.Column referencedColumn; if (mappedKey.getReferencedColumns().size() == 0) { referencedColumn = referencedTable.getPrimaryKey().getColumn(columnIndex); } else { referencedColumn = (org.hibernate.mapping.Column) mappedKey.getReferencedColumns().get(columnIndex); } ForeignKey fkey = new ForeignKey(); fkey.setFkCatalogSchema(m_catalogSchema); fkey.setFkColumn(getColumnName(column)); fkey.setFkName(mappedKey.getName().toLowerCase()); fkey.setFkTable(getTableName(table)); fkey.setKeySeq(String.valueOf(DEFAULT_KEY_SEQ + columnIndex)); fkey.setPkCatalogSchema(m_catalogSchema); fkey.setPkColumn(getColumnName(referencedColumn)); fkey.setPkTable(getTableName(referencedTable)); return fkey; }
From source file:com.vecna.dbDiff.hibernate.HibernateMappingsConverter.java
License:Apache License
/** * Convert a Hibernate column representation to a {@link Column} object. * @param mappedColumn the Hibernate column. * @param owner the table that contains the column. * @param ordinal column's ordinal in the table. * @return a {@link Column} representation of the same column. */// w w w .j a v a 2s . com private Column convertColumn(org.hibernate.mapping.Column mappedColumn, org.hibernate.mapping.Table owner, int ordinal) { Column column = new Column(m_catalogSchema, getColumnName(mappedColumn), getTableName(owner)); ColumnType type = new ColumnType(mappedColumn.getSqlTypeCode(m_mapping), mappedColumn.getSqlType(m_dialect, m_mapping)); column.setColumnType(type); m_dbSpecificMappingInfo.getTypeMapper().mapType(column); if (NUMERIC_TYPES.contains(column.getType())) { if (mappedColumn.getPrecision() != org.hibernate.mapping.Column.DEFAULT_PRECISION) { column.setColumnSize(mappedColumn.getPrecision()); } } else if ("character".equals(mappedColumn.getValue().getType().getName())) { column.setColumnSize(1); } else if (!"binary".equals(mappedColumn.getValue().getType().getName()) && mappedColumn.getLength() != org.hibernate.mapping.Column.DEFAULT_LENGTH) { column.setColumnSize(mappedColumn.getLength()); } column.setDefault(mappedColumn.getDefaultValue()); boolean notNull = !mappedColumn.isNullable() || (owner.getPrimaryKey() != null && owner.getPrimaryKey().getColumns().contains(mappedColumn)); column.setIsNullable(!notNull); column.setOrdinal(ordinal); column.setDefault(mappedColumn.getDefaultValue()); return column; }
From source file:com.xpn.xwiki.store.migration.hibernate.R40000XWIKI6990DataMigration.java
License:Open Source License
/** * Append a drop primary key constraint command for the given table. * * @param sb append the result into this string builder * @param table the table/*w w w . j a v a2 s .com*/ */ private void appendDropPrimaryKey(StringBuilder sb, Table table) { final String tableName = table.getName(); String pkName = table.getPrimaryKey().getName(); // MS-SQL require a constraints name, and the one provided from the mapping is necessarily appropriate // since during database creation, that name has not been used, and a name has been assigned by the // database itself. We need to retrieve that name from the schema. if (this.isMSSQL) { try { pkName = getStore().failSafeExecuteRead(getXWikiContext(), new HibernateCallback<String>() { @Override public String doInHibernate(Session session) throws HibernateException { // Retrieve the constraint name from the database return (String) session .createSQLQuery("SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS" + " WHERE TABLE_NAME = :tableName AND CONSTRAINT_TYPE = 'PRIMARY KEY'") .setString("tableName", tableName).uniqueResult(); } }); } catch (Exception e) { // ignored since it is really unlikely to happen logger.debug("Fail retrieving the primary key constraints name", e); } } sb.append(" <dropPrimaryKey tableName=\"").append(tableName); if (pkName != null) { sb.append("\" constraintName=\"").append(pkName); } sb.append("\"/>\n"); }