public void validateColumns(Dialect dialect, Mapping mapping, TableMetadata tableInfo) { Iterator iter = getColumnIterator(); while (iter.hasNext()) { Column col = (Column) iter.next(); ColumnMetadata columnInfo = tableInfo.getColumnMetadata(col.getName()); if (columnInfo == null) { throw new HibernateException( "Missing column: " + col.getName() + " in " + Table.qualify( tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName())); } else { final boolean typesMatch = col.getSqlType(dialect, mapping) .toLowerCase(Locale.ROOT) .startsWith(columnInfo.getTypeName().toLowerCase(Locale.ROOT)) || columnInfo.getTypeCode() == col.getSqlTypeCode(mapping); if (!typesMatch) { throw new HibernateException( "Wrong column type in " + Table.qualify( tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName()) + " for column " + col.getName() + ". Found: " + columnInfo.getTypeName().toLowerCase(Locale.ROOT) + ", expected: " + col.getSqlType(dialect, mapping)); } } } }
private void buildColumnAnnotation( Selectable selectable, StringBuffer annotations, boolean insertable, boolean updatable) { if (selectable.isFormula()) { annotations .append("@") .append(importType("org.hibernate.annotations.Formula")) .append("(value=\"") .append(selectable.getText()) .append("\")"); } else { Column column = (Column) selectable; annotations .append("@" + importType("javax.persistence.Column") + "(name=\"") .append(column.getName()) .append("\""); appendCommonColumnInfo(annotations, column, insertable, updatable); if (column.getPrecision() != Column.DEFAULT_PRECISION) { // the default is actually 0 in spec annotations.append(", precision=").append(column.getPrecision()); } if (column.getScale() != Column.DEFAULT_SCALE) { // default is actually 0 in spec annotations.append(", scale=").append(column.getScale()); } else if (column.getLength() != 255) { annotations.append(", length=").append(column.getLength()); } // TODO support secondary table annotations.append(")"); } }
public void testForeignKeyColumnBinding() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " String description \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " String name \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestManySide"); Column column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
private void bindColumnsToVersioning(Table table, RootClass rc, Set processed, Mapping mapping) { TableIdentifier identifier = TableIdentifier.create(table); String optimisticLockColumnName = revengStrategy.getOptimisticLockColumnName(identifier); if (optimisticLockColumnName != null) { Column column = table.getColumn(new Column(optimisticLockColumnName)); if (column == null) { log.warn( "Column " + column + " wanted for <version>/<timestamp> not found in " + identifier); } else { bindVersionProperty(table, identifier, column, rc, processed, mapping); } } else { log.debug("Scanning " + identifier + " for <version>/<timestamp> columns."); Iterator columnIterator = table.getColumnIterator(); while (columnIterator.hasNext()) { Column column = (Column) columnIterator.next(); boolean useIt = revengStrategy.useColumnForOptimisticLock(identifier, column.getName()); if (useIt && !processed.contains(column)) { bindVersionProperty(table, identifier, column, rc, processed, mapping); return; } } log.debug( "No columns reported while scanning for <version>/<timestamp> columns in " + identifier); } }
@SuppressWarnings("unchecked") public List<T> findByText2(String searchText, String sortColumn, boolean ascending) { List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault); String query = "select * from " + schemaName + "." + tableName + " where "; Iterator<Column> it = cols.iterator(); while (it.hasNext()) { Column col = it.next(); String colName = col.getName(); String propName = HibernateUtil.convertToHibernatePropertyName(colName); String type = HibernateUtil.getPropertyType(persistentClass, propName); String condition = null; if (type != null) { if (type.equals("integer") || type.equals("smallint")) { try { Integer.valueOf(searchText); condition = colName + "=" + searchText; } catch (NumberFormatException ex) { } } else if (type.equals("timestamp")) { try { Integer.valueOf(searchText); condition = "( YEAR(" + colName + ") = " + searchText + " OR " + " MONTH(" + colName + ") = " + searchText + " OR " + " DAY(" + colName + ") = " + searchText + ")"; } catch (NumberFormatException ex) { } } else if (type.equals("string") || type.equals("timestamp") || type.equals("date")) condition = colName + " ilike '%" + searchText + "%'"; if (condition != null) if (query.trim().endsWith("where")) query = query + condition; else query = query + " OR " + condition; } System.out.println("\n TYPE ZA KOLONU: " + colName + " JE: " + type + "\n"); } if (sortColumn != null && !sortColumn.equals("")) { if (ascending) query = query + " order by " + sortColumn + " asc"; else query = query + " order by " + sortColumn + " desc"; } System.out.println("\n\n\n FINAL QUERY = " + query + " \n\n\n"); return getSession().createSQLQuery(query).list(); }
/** * Tests that single- and multi-column user type mappings work correctly. Also Checks that the * "sqlType" property is honoured. */ public void testUserTypeMappings() { DefaultGrailsDomainConfiguration config = getDomainConfig(MULTI_COLUMN_USER_TYPE_DEFINITION); PersistentClass persistentClass = config.getClassMapping("Item"); // First check the "name" property and its associated column. Property nameProperty = persistentClass.getProperty("name"); assertEquals(1, nameProperty.getColumnSpan()); assertEquals("name", nameProperty.getName()); Column column = (Column) nameProperty.getColumnIterator().next(); assertEquals("s_name", column.getName()); assertEquals("text", column.getSqlType()); // Next the "other" property. Property otherProperty = persistentClass.getProperty("other"); assertEquals(1, otherProperty.getColumnSpan()); assertEquals("other", otherProperty.getName()); column = (Column) otherProperty.getColumnIterator().next(); assertEquals("other", column.getName()); assertEquals("wrapper-characters", column.getSqlType()); assertEquals(MyUserType.class.getName(), column.getValue().getType().getName()); assertTrue(column.getValue() instanceof SimpleValue); SimpleValue v = (SimpleValue) column.getValue(); assertEquals("myParam1", v.getTypeParameters().get("param1")); assertEquals("myParam2", v.getTypeParameters().get("param2")); // And now for the "price" property, which should have two // columns. Property priceProperty = persistentClass.getProperty("price"); assertEquals(2, priceProperty.getColumnSpan()); assertEquals("price", priceProperty.getName()); Iterator<?> colIter = priceProperty.getColumnIterator(); column = (Column) colIter.next(); assertEquals("value", column.getName()); assertNull("SQL type should have been 'null' for 'value' column.", column.getSqlType()); column = (Column) colIter.next(); assertEquals("currency_code", column.getName()); assertEquals("text", column.getSqlType()); }
public void testDefaultNamingStrategy() { GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String fooName \n" + " String barDescriPtion \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestOneSide"); assertEquals("test_one_side", persistentClass.getTable().getName()); Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next(); assertEquals("foo_name", column.getName()); column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next(); assertEquals("bar_descri_ption", column.getName()); persistentClass = config.getClassMapping("TestManySide"); assertEquals("test_many_side", persistentClass.getTable().getName()); column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("version", column.getName()); column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
private void bindVersionProperty( Table table, TableIdentifier identifier, Column column, RootClass rc, Set processed, Mapping mapping) { processed.add(column); String propertyName = revengStrategy.columnToPropertyName(identifier, column.getName()); Property property = bindBasicProperty(makeUnique(rc, propertyName), table, column, processed, mapping); rc.addProperty(property); rc.setVersion(property); rc.setOptimisticLockMode(Versioning.OPTIMISTIC_LOCK_VERSION); log.debug( "Column " + column.getName() + " will be used for <version>/<timestamp> columns in " + identifier); }
@SuppressWarnings({"unchecked"}) @Test public void testJoinColumnName() { Iterator<Column> columns = getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getColumnIterator(); boolean id1Found = false; boolean id2Found = false; while (columns.hasNext()) { Column column = columns.next(); if ("ID_1".equals(column.getName())) { id1Found = true; } if ("ID_2".equals(column.getName())) { id2Found = true; } } assert id1Found && id2Found; }
private Property bindMeta(Property property, TableIdentifier identifier) { Iterator columnIterator = property.getValue().getColumnIterator(); while (columnIterator.hasNext()) { Column col = (Column) columnIterator.next(); Map map = revengStrategy.columnToMetaAttributes(identifier, col.getName()); if (map != null) { // TODO: merge from each column ? property.setMetaAttributes(map); } } return property; }
@SuppressWarnings("unchecked") public List<T> findByText(String searchText, String sortProp, boolean ascending) { List<Column> cols = HibernateUtil.getColumns(persistentClass.getName(), excludeDefault); Iterator<Column> it = cols.iterator(); Criteria crit = getSession().createCriteria(persistentClass); Disjunction disjunction = Restrictions.disjunction(); while (it.hasNext()) { Column col = it.next(); String colName = col.getName(); String propName = HibernateUtil.convertToHibernatePropertyName(colName); String type = HibernateUtil.getPropertyType(persistentClass, propName); if (type != null) { if (type.equals("integer") || type.equals("smallint")) { try { Integer.valueOf(searchText); Criterion criterium = Restrictions.eq(propName, Integer.valueOf(searchText)); disjunction.add(criterium); } catch (NumberFormatException ex) { } } else if (type.equals("string")) { Criterion criterium = Restrictions.ilike(propName, searchText, MatchMode.ANYWHERE); disjunction.add(criterium); } /*else if(type.equals("timestamp")){ Disjunction dis = Restrictions.disjunction(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { dis.add(Restrictions.eq(propName, format.parse(searchText))); } catch (ParseException e) { } try{ Integer.valueOf(searchText); dis.add(Restrictions.sqlRestriction( "YEAR(DATE("+colName+"))="+searchText+ " OR " + "MONTH(DATE("+colName+"))="+searchText+ " OR " + "DAY(DATE("+colName+"))="+searchText)); } catch(NumberFormatException ex) { } disjunction.add(dis); }*/ } } crit.add(disjunction); if (sortProp != null && !sortProp.equals("")) { if (ascending) crit.addOrder(Order.asc(sortProp)); else crit.addOrder(Order.desc(sortProp)); } return crit.list(); }
public void visit(Configuration cfg, Table table, Column col, IssueCollector pc) { if (currentDbTable == null) { return; } Column dbColumn = currentDbTable.getColumn(new Column(col.getName())); if (dbColumn == null) { pc.reportIssue( new Issue( "SCHEMA_COLUMN_MISSING", Issue.HIGH_PRIORITY, table(table) + " is missing column: " + col.getName())); } else { // TODO: this needs to be able to know if a type is truly compatible or not. Right now it // requires an exact match. // String sqlType = col.getSqlType( dialect, mapping ); int dbTypeCode = dbColumn.getSqlTypeCode().intValue(); int modelTypeCode = col.getSqlTypeCode(mapping); // TODO: sqltype name string if (!(dbTypeCode == modelTypeCode)) { pc.reportIssue( new Issue( "SCHEMA_COLUMN_TYPE_MISMATCH", Issue.NORMAL_PRIORITY, table(table) + " has a wrong column type for " + col.getName() + ", expected: " + JDBCToHibernateTypeHelper.getJDBCTypeName(modelTypeCode) + " but was " + JDBCToHibernateTypeHelper.getJDBCTypeName(dbTypeCode) + " in db")); } } }
public static boolean isColumnPresent(String tableName, String columnName, Configuration cfg) { final Iterator<Table> tables = (Iterator<Table>) cfg.getTableMappings(); while (tables.hasNext()) { Table table = tables.next(); if (tableName.equals(table.getName())) { Iterator<Column> columns = (Iterator<Column>) table.getColumnIterator(); while (columns.hasNext()) { Column column = columns.next(); if (columnName.equals(column.getName())) { return true; } } } } return false; }
/** * @param table * @param rc * @param primaryKey */ private void bindColumnsToProperties( Table table, RootClass rc, Set processedColumns, Mapping mapping) { for (Iterator iterator = table.getColumnIterator(); iterator.hasNext(); ) { Column column = (Column) iterator.next(); if (!processedColumns.contains(column)) { checkColumn(column); String propertyName = revengStrategy.columnToPropertyName(TableIdentifier.create(table), column.getName()); Property property = bindBasicProperty( makeUnique(rc, propertyName), table, column, processedColumns, mapping); rc.addProperty(property); } } }
/** Test for GRAILS-4200 */ public void testEmbeddedComponentMapping() { DefaultGrailsDomainConfiguration config = getDomainConfig( "class Widget {\n" + " Long id \n" + " Long version \n" + " EmbeddedWidget ew \n" + " static embedded = ['ew']\n" + "}\n" + " class EmbeddedWidget {\n" + " String ew\n" + " static mapping = {\n" + " ew column: 'widget_name'\n" + " }\n" + " }"); Table tableMapping = getTableMapping("widget", config); Column embeddedComponentMappedColumn = tableMapping.getColumn(new Column("widget_name")); assertNotNull(embeddedComponentMappedColumn); assertEquals("widget_name", embeddedComponentMappedColumn.getName()); }
public void testCustomNamingStrategy() throws Exception { // somewhat artificial in that it doesn't test that setting the property // in DataSource.groovy works, but that's handled in DataSourceConfigurationTests GrailsDomainBinder.configureNamingStrategy(CustomNamingStrategy.class); GroovyClassLoader cl = new GroovyClassLoader(); GrailsDomainClass oneClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestOneSide {\n" + " Long id \n" + " Long version \n" + " String fooName \n" + " String barDescriPtion \n" + "}")); GrailsDomainClass domainClass = new DefaultGrailsDomainClass( cl.parseClass( "class TestManySide {\n" + " Long id \n" + " Long version \n" + " TestOneSide testOneSide \n" + "\n" + " static mapping = {\n" + " columns {\n" + " testOneSide column:'EXPECTED_COLUMN_NAME'" + " }\n" + " }\n" + "}")); DefaultGrailsDomainConfiguration config = getDomainConfig(cl, new Class[] {oneClass.getClazz(), domainClass.getClazz()}); PersistentClass persistentClass = config.getClassMapping("TestOneSide"); assertEquals("table_TestOneSide", persistentClass.getTable().getName()); Column column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("col_id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("col_version", column.getName()); column = (Column) persistentClass.getProperty("fooName").getColumnIterator().next(); assertEquals("col_fooName", column.getName()); column = (Column) persistentClass.getProperty("barDescriPtion").getColumnIterator().next(); assertEquals("col_barDescriPtion", column.getName()); persistentClass = config.getClassMapping("TestManySide"); assertEquals("table_TestManySide", persistentClass.getTable().getName()); column = (Column) persistentClass.getProperty("id").getColumnIterator().next(); assertEquals("col_id", column.getName()); column = (Column) persistentClass.getProperty("version").getColumnIterator().next(); assertEquals("col_version", column.getName()); column = (Column) persistentClass.getProperty("testOneSide").getColumnIterator().next(); assertEquals("EXPECTED_COLUMN_NAME", column.getName()); }
/** * @param column * @param generatedIdentifier * @return */ private String guessAndAlignType( Table table, Column column, Mapping mapping, boolean generatedIdentifier) { // TODO: this method mutates the column if the types does not match...not good. // maybe we should copy the column instead before calling this method. Integer sqlTypeCode = column.getSqlTypeCode(); String location = "Table: " + Table.qualify(table.getCatalog(), table.getSchema(), table.getQuotedName()) + " column: " + column.getQuotedName(); if (sqlTypeCode == null) { throw new JDBCBinderException("sqltype is null for " + location); } String preferredHibernateType = revengStrategy.columnToHibernateTypeName( TableIdentifier.create(table), column.getName(), sqlTypeCode.intValue(), column.getLength(), column.getPrecision(), column.getScale(), column.isNullable(), generatedIdentifier); Type wantedType = TypeFactory.heuristicType(preferredHibernateType); if (wantedType != null) { int[] wantedSqlTypes = wantedType.sqlTypes(mapping); if (wantedSqlTypes.length > 1) { throw new JDBCBinderException( "The type " + preferredHibernateType + " found on " + location + " spans multiple columns. Only single column types allowed."); } int wantedSqlType = wantedSqlTypes[0]; if (wantedSqlType != sqlTypeCode.intValue()) { log.debug( "Sql type mismatch for " + location + " between DB and wanted hibernate type. Sql type set to " + typeCodeName(sqlTypeCode.intValue()) + " instead of " + typeCodeName(wantedSqlType)); column.setSqlTypeCode(new Integer(wantedSqlType)); } } else { log.debug( "No Hibernate type found for " + preferredHibernateType + ". Most likely cause is a missing UserType class."); } if (preferredHibernateType == null) { throw new JDBCBinderException( "Could not find javatype for " + typeCodeName(sqlTypeCode.intValue())); } return preferredHibernateType; }
/** * Basically create an [classname]Id.class and add properties for it. * * @param rc * @param compositeKeyColumns * @param processed * @return */ private SimpleValue handleCompositeKey( RootClass rc, Set processedColumns, List keyColumns, Mapping mapping) { Component pkc = new Component(rc); pkc.setMetaAttributes(Collections.EMPTY_MAP); pkc.setEmbedded(false); String compositeIdName = revengStrategy.tableToCompositeIdName(TableIdentifier.create(rc.getTable())); if (compositeIdName == null) { compositeIdName = revengStrategy.classNameToCompositeIdName(rc.getClassName()); } pkc.setComponentClassName(compositeIdName); Table table = rc.getTable(); List list = null; if (cfg.preferBasicCompositeIds()) { list = new ArrayList(keyColumns); } else { list = findForeignKeys(table.getForeignKeyIterator(), keyColumns); } for (Iterator iter = list.iterator(); iter.hasNext(); ) { Object element = iter.next(); Property property; if (element instanceof Column) { Column column = (Column) element; if (processedColumns.contains(column)) { throw new JDBCBinderException( "Binding column twice for primary key should not happen: " + column); } else { checkColumn(column); String propertyName = revengStrategy.columnToPropertyName(TableIdentifier.create(table), column.getName()); property = bindBasicProperty( makeUnique(pkc, propertyName), table, column, processedColumns, mapping); processedColumns.add(column); } } else if (element instanceof ForeignKeyForColumns) { ForeignKeyForColumns fkfc = (ForeignKeyForColumns) element; ForeignKey foreignKey = fkfc.key; String propertyName = revengStrategy.foreignKeyToEntityName( foreignKey.getName(), TableIdentifier.create(foreignKey.getTable()), foreignKey.getColumns(), TableIdentifier.create(foreignKey.getReferencedTable()), foreignKey.getReferencedColumns(), true); property = bindManyToOne(makeUnique(pkc, propertyName), true, table, foreignKey, processedColumns); processedColumns.addAll(fkfc.columns); } else { throw new JDBCBinderException("unknown thing"); } markAsUseInEquals(property); pkc.addProperty(property); } return pkc; }
@SuppressWarnings({"unchecked"}) public void doSecondPass(Map persistentClasses) throws MappingException { PersistentClass referencedPersistentClass = (PersistentClass) persistentClasses.get(referencedEntityName); // TODO better error names if (referencedPersistentClass == null) { throw new AnnotationException("Unknown entity name: " + referencedEntityName); } if (!(referencedPersistentClass.getIdentifier() instanceof Component)) { throw new AssertionFailure( "Unexpected identifier type on the referenced entity when mapping a @MapsId: " + referencedEntityName); } Component referencedComponent = (Component) referencedPersistentClass.getIdentifier(); Iterator<Property> properties = referencedComponent.getPropertyIterator(); // prepare column name structure boolean isExplicitReference = true; Map<String, Ejb3JoinColumn> columnByReferencedName = new HashMap<String, Ejb3JoinColumn>(joinColumns.length); for (Ejb3JoinColumn joinColumn : joinColumns) { final String referencedColumnName = joinColumn.getReferencedColumn(); if (referencedColumnName == null || BinderHelper.isEmptyAnnotationValue(referencedColumnName)) { break; } // JPA 2 requires referencedColumnNames to be case insensitive columnByReferencedName.put(referencedColumnName.toLowerCase(), joinColumn); } // try default column orientation int index = 0; if (columnByReferencedName.isEmpty()) { isExplicitReference = false; for (Ejb3JoinColumn joinColumn : joinColumns) { columnByReferencedName.put("" + index, joinColumn); index++; } index = 0; } while (properties.hasNext()) { Property referencedProperty = properties.next(); if (referencedProperty.isComposite()) { throw new AssertionFailure( "Unexpected nested component on the referenced entity when mapping a @MapsId: " + referencedEntityName); } else { Property property = new Property(); property.setName(referencedProperty.getName()); property.setNodeName(referencedProperty.getNodeName()); // FIXME set optional? // property.setOptional( property.isOptional() ); property.setPersistentClass(component.getOwner()); property.setPropertyAccessorName(referencedProperty.getPropertyAccessorName()); SimpleValue value = new SimpleValue(mappings, component.getTable()); property.setValue(value); final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue(); value.setTypeName(referencedValue.getTypeName()); value.setTypeParameters(referencedValue.getTypeParameters()); final Iterator<Column> columns = referencedValue.getColumnIterator(); if (joinColumns[0].isNameDeferred()) { joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns( referencedPersistentClass, columns, value); } else { // FIXME take care of Formula while (columns.hasNext()) { Column column = columns.next(); final Ejb3JoinColumn joinColumn; String logicalColumnName = null; if (isExplicitReference) { final String columnName = column.getName(); logicalColumnName = mappings.getLogicalColumnName(columnName, referencedPersistentClass.getTable()); // JPA 2 requires referencedColumnNames to be case insensitive joinColumn = columnByReferencedName.get(logicalColumnName.toLowerCase()); } else { joinColumn = columnByReferencedName.get("" + index); index++; } if (joinColumn == null && !joinColumns[0].isNameDeferred()) { throw new AnnotationException( isExplicitReference ? "Unable to find column reference in the @MapsId mapping: " + logicalColumnName : "Implicit column reference in the @MapsId mapping fails, try to use explicit referenceColumnNames: " + referencedEntityName); } final String columnName = joinColumn == null || joinColumn.isNameDeferred() ? "tata_" + column.getName() : joinColumn.getName(); value.addColumn(new Column(columnName)); column.setValue(value); } } component.addProperty(property); } } }
public Iterator sqlAlterStrings( Dialect dialect, Mapping p, TableMetadata tableInfo, String defaultCatalog, String defaultSchema) throws HibernateException { StringBuffer root = new StringBuffer("alter table ") .append(getQualifiedName(dialect, defaultCatalog, defaultSchema)) .append(' ') .append(dialect.getAddColumnString()); 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. StringBuffer alter = new StringBuffer(root.toString()) .append(' ') .append(column.getQuotedName(dialect)) .append(' ') .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"); } } 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)); results.add(alter.toString()); } } return results.iterator(); }
public Iterator sqlAlterStrings( Dialect dialect, Mapping p, TableInformation tableInfo, String defaultCatalog, String defaultSchema) throws HibernateException { StringBuilder root = new StringBuilder("alter table ") .append(getQualifiedName(dialect, defaultCatalog, defaultSchema)) .append(' ') .append(dialect.getAddColumnString()); Iterator iter = getColumnIterator(); List results = new ArrayList(); while (iter.hasNext()) { final Column column = (Column) iter.next(); final ColumnInformation columnInfo = tableInfo.getColumn(Identifier.toIdentifier(column.getName(), column.isQuoted())); if (columnInfo == null) { // the column doesnt exist at all. StringBuilder alter = new StringBuilder(root.toString()) .append(' ') .append(column.getQuotedName(dialect)) .append(' ') .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()); results.add(alter.toString()); } } if (results.isEmpty()) { Logger.getLogger(SchemaUpdate.class) .debugf("No alter strings for table : %s", getQuotedName()); } return results.iterator(); }
private PrimaryKeyInfo bindPrimaryKeyToProperties( Table table, RootClass rc, Set processed, Mapping mapping, DatabaseCollector collector) { SimpleValue id = null; String idPropertyname = null; PrimaryKeyInfo pki = new PrimaryKeyInfo(); List keyColumns = null; if (table.getPrimaryKey() != null) { keyColumns = table.getPrimaryKey().getColumns(); } else { log.debug("No primary key found for " + table + ", using all properties as the identifier."); keyColumns = new ArrayList(); Iterator iter = table.getColumnIterator(); while (iter.hasNext()) { Column col = (Column) iter.next(); keyColumns.add(col); } } final TableIdentifier tableIdentifier = TableIdentifier.create(table); String tableIdentifierStrategyName = "assigned"; boolean naturalId; if (keyColumns.size() > 1) { log.debug( "id strategy for " + rc.getEntityName() + " since it has a multiple column primary key"); naturalId = true; id = handleCompositeKey(rc, processed, keyColumns, mapping); idPropertyname = revengStrategy.tableToIdentifierPropertyName(tableIdentifier); if (idPropertyname == null) { idPropertyname = "id"; } } else { pki.suggestedStrategy = revengStrategy.getTableIdentifierStrategyName(tableIdentifier); String suggestedStrategy = pki.suggestedStrategy; if (suggestedStrategy == null) { suggestedStrategy = collector.getSuggestedIdentifierStrategy( tableIdentifier.getCatalog(), tableIdentifier.getSchema(), tableIdentifier.getName()); if (suggestedStrategy == null) { suggestedStrategy = "assigned"; } tableIdentifierStrategyName = suggestedStrategy; } else { tableIdentifierStrategyName = suggestedStrategy; } naturalId = "assigned".equals(tableIdentifierStrategyName); Column pkc = (Column) keyColumns.get(0); checkColumn(pkc); id = bindColumnToSimpleValue(table, pkc, mapping, !naturalId); idPropertyname = revengStrategy.tableToIdentifierPropertyName(tableIdentifier); if (idPropertyname == null) { idPropertyname = revengStrategy.columnToPropertyName(tableIdentifier, pkc.getName()); } processed.add(pkc); } id.setIdentifierGeneratorStrategy(tableIdentifierStrategyName); pki.suggestedProperties = revengStrategy.getTableIdentifierProperties(tableIdentifier); id.setIdentifierGeneratorProperties(pki.suggestedProperties); if (naturalId) { id.setNullValue("undefined"); } Property property = makeProperty( tableIdentifier, makeUnique(rc, idPropertyname), id, true, true, false, null, null); rc.setIdentifierProperty(property); rc.setIdentifier(id); return pki; }