Author: max.andersen(a)jboss.com
Date: 2009-03-02 09:36:20 -0500 (Mon, 02 Mar 2009)
New Revision: 16054
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java
Log:
backref tests and changed back to use "all" as default for cascades to not break
seam/jpa users.
Modified:
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java 2009-03-02
10:31:56 UTC (rev 16053)
+++
branches/Branch_3_2/HibernateExt/tools/src/java/org/hibernate/cfg/JDBCBinder.java 2009-03-02
14:36:20 UTC (rev 16054)
@@ -65,9 +65,9 @@
private Settings settings;
private ConnectionProvider connectionProvider;
private static final Log log = LogFactory.getLog(JDBCBinder.class);
-
+
private final Mappings mappings;
-
+
private final JDBCMetaDataConfiguration cfg;
private ReverseEngineeringStrategy revengStrategy;
@@ -83,54 +83,54 @@
}
/**
- *
+ *
*/
public void readFromDatabase(String catalog, String schema, Mapping mapping) {
-
+
this.connectionProvider = settings.getConnectionProvider();
-
+
try {
-
- DatabaseCollector collector = readDatabaseSchema(catalog, schema);
+
+ DatabaseCollector collector = readDatabaseSchema(catalog, schema);
createPersistentClasses(collector, mapping); //move this to a different step!
- }
+ }
catch (SQLException e) {
throw settings.getSQLExceptionConverter().convert(e, "Reading from
database", null);
- }
+ }
finally {
if(connectionProvider!=null) connectionProvider.close();
}
-
+
}
/**
* Read JDBC Metadata from the database. Does not create any classes or other ORM
releated structures.
- *
+ *
* @param catalog
* @param schema
- * @return
+ * @return
* @throws SQLException
*/
public DatabaseCollector readDatabaseSchema(String catalog, String schema) throws
SQLException {
// use default from settings if nothing else specified.
catalog = catalog!=null ? catalog : settings.getDefaultCatalogName();
schema = schema!=null ? schema : settings.getDefaultSchemaName();
-
+
JDBCReader reader =
JDBCReaderFactory.newJDBCReader(cfg.getProperties(),settings,revengStrategy);
- DatabaseCollector dbs = new MappingsDatabaseCollector(mappings);
+ DatabaseCollector dbs = new MappingsDatabaseCollector(mappings);
reader.readDatabaseSchema(dbs, catalog, schema);
return dbs;
}
-
+
/**
* @param manyToOneCandidates
* @param mappings2
*/
private void createPersistentClasses(DatabaseCollector collector, Mapping mapping) {
Map manyToOneCandidates = collector.getOneToManyCandidates();
-
+
for (Iterator iter = mappings.iterateTables(); iter.hasNext();) {
Table table = (Table) iter.next();
if(table.getColumnSpan()==0) {
@@ -144,23 +144,23 @@
continue;
// TODO: just create one big embedded composite id instead.
}*/
-
+
if(revengStrategy.isManyToManyTable(table)) {
log.debug( "Ignoring " + table + " as class since rev.eng. says it is
a many-to-many" );
continue;
- }
-
+ }
+
RootClass rc = new RootClass();
TableIdentifier tableIdentifier = TableIdentifier.create(table);
String className = revengStrategy.tableToClassName( tableIdentifier );
rc.setEntityName( className );
- rc.setClassName( className );
+ rc.setClassName( className );
rc.setProxyInterfaceName( rc.getEntityName() ); // TODO: configurable ?
rc.setLazy(true);
-
+
rc.setMetaAttributes( safeMeta(revengStrategy.tableToMetaAttributes( tableIdentifier
)) );
-
-
+
+
rc.setDiscriminatorValue( rc.getEntityName() );
rc.setTable(table);
try {
@@ -169,13 +169,13 @@
// TODO: detect this and generate a "permutation" of it ?
PersistentClass class1 = mappings.getClass(dme.getName());
Table table2 = class1.getTable();
- throw new JDBCBinderException("Duplicate class name '" +
rc.getEntityName() + "' generated for '" + table + "'. Same
name where generated for '" + table2 + "'");
+ throw new JDBCBinderException("Duplicate class name '" +
rc.getEntityName() + "' generated for '" + table + "'. Same
name where generated for '" + table2 + "'");
}
mappings.addImport( rc.getEntityName(), rc.getEntityName() );
-
+
Set processed = new HashSet();
-
-
+
+
PrimaryKeyInfo pki = bindPrimaryKeyToProperties(table, rc, processed, mapping,
collector);
bindColumnsToVersioning(table, rc, processed, mapping);
bindOutgoingForeignKeys(table, rc, processed);
@@ -183,29 +183,29 @@
List incomingForeignKeys = (List) manyToOneCandidates.get( rc.getEntityName() );
bindIncomingForeignKeys(rc, processed, incomingForeignKeys, mapping);
updatePrimaryKey(rc, pki);
-
+
}
-
+
}
private void updatePrimaryKey(RootClass rc, PrimaryKeyInfo pki) {
SimpleValue idValue = (SimpleValue) rc.getIdentifierProperty().getValue();
-
+
Properties defaultStrategyProperties = new Properties();
- Property constrainedOneToOne = getConstrainedOneToOne(rc);
+ Property constrainedOneToOne = getConstrainedOneToOne(rc);
if(constrainedOneToOne!=null) {
if(pki.suggestedStrategy==null) {
- idValue.setIdentifierGeneratorStrategy("foreign");
+ idValue.setIdentifierGeneratorStrategy("foreign");
}
-
+
if(pki.suggestedProperties==null) {
defaultStrategyProperties.setProperty("property",
constrainedOneToOne.getName());
idValue.setIdentifierGeneratorProperties(defaultStrategyProperties);
}
}
-
-
-
+
+
+
}
private Property getConstrainedOneToOne(RootClass rc) {
@@ -221,7 +221,7 @@
}
return null;
}
-
+
private Map safeMeta(Map map) {
if(map==null) {
return new HashMap();
@@ -235,18 +235,18 @@
if(foreignKeys!=null) {
for (Iterator iter = foreignKeys.iterator(); iter.hasNext();) {
ForeignKey foreignKey = (ForeignKey) iter.next();
-
+
if(revengStrategy.excludeForeignKeyAsCollection(
- foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+ foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
foreignKey.getReferencedColumns())) {
log.debug("Rev.eng excluded one-to-many or one-to-one for foreignkey " +
foreignKey.getName());
} else if (revengStrategy.isOneToOne(foreignKey)){
Property property = bindOneToOne(rc, foreignKey.getTable(), foreignKey, processed,
false, true);
rc.addProperty(property);
- } else {
+ } else {
Property property = bindOneToMany(rc, foreignKey, processed, mapping);
rc.addProperty(property);
}
@@ -254,11 +254,11 @@
}
}
-
+
private Property bindOneToOne(PersistentClass rc, Table targetTable,
ForeignKey fk, Set processedColumns, boolean constrained, boolean
inverseProperty) {
-
+
OneToOne value = new OneToOne(targetTable, rc);
value.setReferencedEntityName(revengStrategy
.tableToClassName(TableIdentifier.create(targetTable)));
@@ -286,63 +286,64 @@
}
value.setFetchMode(FetchMode.SELECT);
-
+
value.setConstrained(constrained);
value.setForeignKeyType( constrained ?
ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT :
ForeignKeyDirection.FOREIGN_KEY_TO_PARENT );
-
+
return makeEntityProperty(propertyName, true, targetTable, fk, value,
inverseProperty);
//return makeProperty(TableIdentifier.create(targetTable), propertyName, value,
// true, true, value.getFetchMode() != FetchMode.JOIN, null, null);
}
/**
- * @param mutable
+ * @param mutable
* @param table
* @param fk
- * @param columnsToBind
+ * @param columnsToBind
* @param processedColumns
* @param rc
- * @param propName
+ * @param propName
*/
private Property bindManyToOne(String propertyName, boolean mutable, Table table,
ForeignKey fk, Set processedColumns) {
ManyToOne value = new ManyToOne(table);
value.setReferencedEntityName( fk.getReferencedEntityName() );
Iterator columns = fk.getColumnIterator();
- while ( columns.hasNext() ) {
+ while ( columns.hasNext() ) {
Column fkcolumn = (Column) columns.next();
checkColumn(fkcolumn);
value.addColumn(fkcolumn);
processedColumns.add(fkcolumn);
}
value.setFetchMode(FetchMode.SELECT);
-
+
return makeEntityProperty(propertyName, mutable, table, fk, value, false);
}
private Property makeCollectionProperty(String propertyName, boolean mutable,
Table table, ForeignKey fk, Collection value, boolean inverseProperty) {
AssociationInfo fkei =
inverseProperty?revengStrategy.foreignKeyToInverseAssociationInfo(fk):revengStrategy.foreignKeyToAssociationInfo(fk);
-
+
String fetchMode = null;
String cascade = null;
boolean update = mutable;
boolean insert = mutable;
- if(fkei != null){
+ if(fkei != null){
cascade = fkei.getCascade();
+ if(cascade==null) cascade = "all"; //To ensure collections cascade to
be compatible with Seam-gen and previous behavior.
if(fkei.getUpdate()!=null) {
update = fkei.getUpdate().booleanValue();
}
if(fkei.getInsert()!=null) {
insert = fkei.getInsert().booleanValue();
}
-
+
fetchMode = fkei.getFetch();
-
-
+
+
}
if(FetchMode.JOIN.toString().equalsIgnoreCase(fetchMode)) {
@@ -362,13 +363,13 @@
private Property makeEntityProperty(String propertyName, boolean mutable,
Table table, ForeignKey fk, ToOne value, boolean inverseProperty) {
AssociationInfo fkei =
inverseProperty?revengStrategy.foreignKeyToInverseAssociationInfo(fk):revengStrategy.foreignKeyToAssociationInfo(fk);
-
+
String fetchMode = null;
String cascade = null;
boolean update = mutable;
boolean insert = mutable;
- if(fkei != null){
+ if(fkei != null){
cascade = fkei.getCascade();
if(fkei.getUpdate()!=null) {
update = fkei.getUpdate().booleanValue();
@@ -376,10 +377,10 @@
if(fkei.getInsert()!=null) {
insert = fkei.getInsert().booleanValue();
}
-
+
fetchMode = fkei.getFetch();
-
-
+
+
}
if(FetchMode.JOIN.toString().equalsIgnoreCase(fetchMode)) {
@@ -402,25 +403,25 @@
* @param object
*/
private Property bindOneToMany(PersistentClass rc, ForeignKey foreignKey, Set processed,
Mapping mapping) {
-
+
Table collectionTable = foreignKey.getTable();
Collection collection = new org.hibernate.mapping.Set(rc); // MASTER TODO: allow
overriding collection type
collection.setCollectionTable(collectionTable); // CHILD+
-
-
-
+
+
+
boolean manyToMany = revengStrategy.isManyToManyTable( collectionTable );
if(manyToMany) {
//log.debug("Rev.eng said here is a many-to-many");
// TODO: handle "the other side should influence the name"
}
-
+
if(manyToMany) {
-
+
ManyToOne element = new ManyToOne( collection.getCollectionTable() );
//TODO: find the other foreignkey and choose the other side.
Iterator foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator();
@@ -428,30 +429,30 @@
while ( foreignKeyIterator.hasNext() ) {
Object next = foreignKeyIterator.next();
if(next!=foreignKey) {
- keys.add(next);
+ keys.add(next);
}
}
-
+
if(keys.size()>1) {
throw new JDBCBinderException("more than one other foreign key to choose
from!"); // todo: handle better ?
}
-
+
ForeignKey fk = (ForeignKey) keys.get( 0 );
String tableToClassName = bindCollection( rc, foreignKey, fk, collection );
-
+
element.setReferencedEntityName( tableToClassName );
element.addColumn( fk.getColumn( 0 ) );
collection.setElement( element );
-
+
} else {
String tableToClassName = bindCollection( rc, foreignKey, null, collection );
-
+
OneToMany oneToMany = new OneToMany( collection.getOwner() );
-
+
oneToMany.setReferencedEntityName( tableToClassName ); // Child
mappings.addSecondPass( new JDBCCollectionSecondPass(mappings, collection) );
-
+
collection.setElement(oneToMany);
}
// bind keyvalue
@@ -469,7 +470,7 @@
SimpleValue keyValue = new DependantValue( collectionTable, referencedKeyValue );
//keyValue.setForeignKeyName("none"); // Avoid creating the foreignkey
//key.setCascadeDeleteEnabled( "cascade".equals(
subnode.attributeValue("on-delete") ) );
- Iterator columnIterator = foreignKey.getColumnIterator();
+ Iterator columnIterator = foreignKey.getColumnIterator();
while ( columnIterator.hasNext() ) {
Column fkcolumn = (Column) columnIterator.next();
if(fkcolumn.getSqlTypeCode()!=null) { // TODO: user defined foreign ref columns does
not have a type set.
@@ -477,18 +478,18 @@
}
keyValue.addColumn( fkcolumn );
}
-
+
collection.setKey(keyValue);
-
+
mappings.addCollection(collection);
-
- return makeCollectionProperty(StringHelper.unqualify( collection.getRole() ), true,
rc.getTable(), foreignKey, collection, true);
+
+ return makeCollectionProperty(StringHelper.unqualify( collection.getRole() ), true,
rc.getTable(), foreignKey, collection, true);
//return makeProperty(TableIdentifier.create( rc.getTable() ), StringHelper.unqualify(
collection.getRole() ), collection, true, true, true, "none", null); // TODO:
cascade isn't all by default
-
-
+
+
}
-
+
private String bindCollection(PersistentClass rc, ForeignKey fromForeignKey, ForeignKey
toForeignKey, Collection collection) {
ForeignKey targetKey = fromForeignKey;
String collectionRole = null;
@@ -496,66 +497,66 @@
boolean collectionInverse = false;
TableIdentifier foreignKeyTable = null;
String tableToClassName;
-
+
if(toForeignKey!=null) {
targetKey = toForeignKey;
}
-
+
boolean uniqueReference = isUniqueReference(targetKey); // TODO: need to look one step
further for many-to-many!
foreignKeyTable = TableIdentifier.create( targetKey.getTable() );
TableIdentifier foreignKeyReferencedTable = TableIdentifier.create(
targetKey.getReferencedTable() );
-
+
if(toForeignKey==null) {
-
+
collectionRole = revengStrategy.foreignKeyToCollectionName(
- fromForeignKey.getName(),
- foreignKeyTable,
- fromForeignKey.getColumns(),
- foreignKeyReferencedTable,
- fromForeignKey.getReferencedColumns(),
+ fromForeignKey.getName(),
+ foreignKeyTable,
+ fromForeignKey.getColumns(),
+ foreignKeyReferencedTable,
+ fromForeignKey.getReferencedColumns(),
uniqueReference
);
-
+
tableToClassName = revengStrategy.tableToClassName( foreignKeyTable );
} else {
-
- collectionRole = revengStrategy.foreignKeyToManyToManyName(
+
+ collectionRole = revengStrategy.foreignKeyToManyToManyName(
fromForeignKey, TableIdentifier.create( fromForeignKey.getTable()), toForeignKey,
uniqueReference );
-
+
tableToClassName = revengStrategy.tableToClassName( foreignKeyReferencedTable );
}
- collectionInverse =
revengStrategy.isForeignKeyCollectionInverse(targetKey.getName(),
- foreignKeyTable,
- targetKey.getColumns(),
- foreignKeyReferencedTable,
+ collectionInverse = revengStrategy.isForeignKeyCollectionInverse(targetKey.getName(),
+ foreignKeyTable,
+ targetKey.getColumns(),
+ foreignKeyReferencedTable,
targetKey.getReferencedColumns());
-
- collectionLazy = revengStrategy.isForeignKeyCollectionLazy(targetKey.getName(),
- foreignKeyTable,
- targetKey.getColumns(),
- foreignKeyReferencedTable,
+
+ collectionLazy = revengStrategy.isForeignKeyCollectionLazy(targetKey.getName(),
+ foreignKeyTable,
+ targetKey.getColumns(),
+ foreignKeyReferencedTable,
targetKey.getReferencedColumns());
-
+
collectionRole = makeUnique(rc,collectionRole);
-
+
String fullRolePath = StringHelper.qualify(rc.getEntityName(), collectionRole);
if (mappings.getCollection(fullRolePath)!=null) {
log.debug(fullRolePath + " found twice!");
}
-
- collection.setRole(fullRolePath); // Master.setOfChildren+
+
+ collection.setRole(fullRolePath); // Master.setOfChildren+
collection.setInverse(collectionInverse); // TODO: allow overriding this
- collection.setLazy(collectionLazy);
+ collection.setLazy(collectionLazy);
collection.setFetchMode(FetchMode.SELECT);
-
-
+
+
return tableToClassName;
}
/** return true if this foreignkey is the only reference from this table to the same
foreign table */
private boolean isUniqueReference(ForeignKey foreignKey) {
-
+
Iterator foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator();
while ( foreignKeyIterator.hasNext() ) {
ForeignKey element = (ForeignKey) foreignKeyIterator.next();
@@ -567,22 +568,22 @@
}
static private class PrimaryKeyInfo {
-
+
String suggestedStrategy = null;
- Properties suggestedProperties = null;
+ Properties suggestedProperties = null;
}
-
-
+
+
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();
@@ -594,21 +595,21 @@
}
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;
@@ -621,31 +622,31 @@
} 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);
+ 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.setIdentifierProperty(property);
rc.setIdentifier(id);
-
+
return pki;
}
@@ -656,20 +657,20 @@
* @param primaryKey
*/
private void bindOutgoingForeignKeys(Table table, RootClass rc, Set processedColumns) {
-
- // Iterate the outgoing foreign keys and create many-to-one's
+
+ // Iterate the outgoing foreign keys and create many-to-one's
for(Iterator iterator = table.getForeignKeyIterator(); iterator.hasNext();) {
ForeignKey foreignKey = (ForeignKey) iterator.next();
-
+
boolean mutable = true;
if ( contains( foreignKey.getColumnIterator(), processedColumns ) ) {
if ( !cfg.preferBasicCompositeIds() ) continue; //it's in the pk, so skip this
one
- mutable = false;
+ mutable = false;
}
-
- if(revengStrategy.excludeForeignKeyAsManytoOne(foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+
+ if(revengStrategy.excludeForeignKeyAsManytoOne(foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
foreignKey.getReferencedColumns())) {
// TODO: if many-to-one is excluded should the column be marked as processed
so it won't show up at all ?
@@ -680,59 +681,59 @@
} else {
boolean isUnique = isUniqueReference(foreignKey);
String propertyName = revengStrategy.foreignKeyToEntityName(
- foreignKey.getName(),
- TableIdentifier.create(foreignKey.getTable() ),
- foreignKey.getColumns(),
+ foreignKey.getName(),
+ TableIdentifier.create(foreignKey.getTable() ),
+ foreignKey.getColumns(),
TableIdentifier.create(foreignKey.getReferencedTable() ),
- foreignKey.getReferencedColumns(),
+ foreignKey.getReferencedColumns(),
isUnique
);
-
+
Property property = bindManyToOne(
makeUnique(rc, propertyName),
mutable,
- table,
+ table,
foreignKey,
processedColumns
);
-
+
rc.addProperty(property);
}
}
}
-
+
/**
* @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,
+
+ Property property = bindBasicProperty(
+ makeUnique(rc,propertyName),
+ table,
+ column,
processedColumns,
mapping
);
-
+
rc.addProperty(property);
- }
+ }
}
}
-
+
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) {
@@ -748,7 +749,7 @@
boolean useIt = revengStrategy.useColumnForOptimisticLock(identifier,
column.getName());
if(useIt && !processed.contains(column)) {
bindVersionProperty( table, identifier, column, rc, processed, mapping );
- return;
+ return;
}
}
log.debug("No columns reported while scanning for
<version>/<timestamp> columns in " + identifier);
@@ -756,7 +757,7 @@
}
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);
@@ -764,18 +765,18 @@
rc.setVersion(property);
rc.setOptimisticLockMode(Versioning.OPTIMISTIC_LOCK_VERSION);
log.debug("Column " + column.getName() + " will be used for
<version>/<timestamp> columns in " + identifier);
-
+
}
private Property bindBasicProperty(String propertyName, Table table, Column column, Set
processedColumns, Mapping mapping) {
SimpleValue value = bindColumnToSimpleValue( table, column, mapping, false );
-
+
return makeProperty(TableIdentifier.create( table ), propertyName, value, true, true,
false, null, null);
}
private SimpleValue bindColumnToSimpleValue(Table table, Column column, Mapping mapping,
boolean generatedIdentifier) {
- SimpleValue value = new SimpleValue(table);
+ SimpleValue value = new SimpleValue(table);
value.addColumn(column);
value.setTypeName(guessAndAlignType(table, column, mapping, generatedIdentifier));
return value;
@@ -804,50 +805,50 @@
/**
* @param column
- * @param generatedIdentifier
+ * @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.
+ // 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(),
+ 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.");
+ 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() ) {
+ 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;
}
@@ -858,25 +859,25 @@
/**
* Basically create an [classname]Id.class and add properties for it.
* @param rc
- * @param compositeKeyColumns
+ * @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);
-
+ 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;
+ Table table = rc.getTable();
+ List list = null;
if (cfg.preferBasicCompositeIds() ) {
list = new ArrayList(keyColumns);
- }
+ }
else {
list = findForeignKeys(table.getForeignKeyIterator(), keyColumns);
}
@@ -886,22 +887,22 @@
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);
- }
+ 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(),
+ foreignKey.getName(),
TableIdentifier.create(foreignKey.getTable() ),
foreignKey.getColumns(), TableIdentifier.create(foreignKey.getReferencedTable() ),
foreignKey.getReferencedColumns(), true
);
@@ -911,10 +912,10 @@
else {
throw new JDBCBinderException("unknown thing");
}
-
+
markAsUseInEquals(property);
pkc.addProperty(property);
-
+
}
return pkc;
@@ -934,22 +935,22 @@
/**
* @param foreignKeyIterator
* @param columns
- * @return
+ * @return
*/
private List findForeignKeys(Iterator foreignKeyIterator, List pkColumns) {
-
+
List tempList = new ArrayList();
while(foreignKeyIterator.hasNext()) {
tempList.add(foreignKeyIterator.next());
}
-
-// Collections.reverse(tempList);
-
+
+// Collections.reverse(tempList);
+
List result = new ArrayList();
Column myPkColumns[] = (Column[]) pkColumns.toArray(new Column[pkColumns.size()]);
-
+
for (int i = 0; i < myPkColumns.length; i++) {
-
+
boolean foundKey = false;
foreignKeyIterator = tempList.iterator();
while(foreignKeyIterator.hasNext()) {
@@ -961,23 +962,23 @@
foreignKeyIterator.remove();
foundKey=true;
break;
- }
+ }
}
if(!foundKey) {
- result.add(myPkColumns[i]);
+ result.add(myPkColumns[i]);
}
-
+
}
-
+
return result;
}
private List columnMatches(Column[] myPkColumns, int offset, ForeignKey key) {
-
+
if(key.getColumnSpan()>(myPkColumns.length-offset)) {
return null; // not enough columns in the key
}
-
+
List columns = new ArrayList();
for (int j = 0; j < key.getColumnSpan(); j++) {
Column column = myPkColumns[j+offset];
@@ -991,7 +992,7 @@
}
static class ForeignKeyForColumns {
-
+
protected final List columns;
protected final ForeignKey key;
@@ -1008,25 +1009,25 @@
prop.setValue(value);
prop.setInsertable(insertable);
prop.setUpdateable(updatable);
- prop.setLazy(lazy);
+ prop.setLazy(lazy);
prop.setCascade(cascade==null?"none":cascade);
- prop.setPropertyAccessorName(propertyAccessorName==null?"property":propertyAccessorName);
+ prop.setPropertyAccessorName(propertyAccessorName==null?"property":propertyAccessorName);
bindMeta(prop, table);
-
+
return prop;
}
-
+
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;
}
@@ -1041,15 +1042,15 @@
private String makeUnique(PersistentClass clazz, String propertyName) {
List list = new ArrayList();
-
+
if( clazz.hasIdentifierProperty() ) {
list.add( clazz.getIdentifierProperty() );
}
-
+
if( clazz.isVersioned() ) {
list.add( clazz.getVersion() );
}
-
+
JoinedIterator iterator = new JoinedIterator(
list.iterator(),clazz.getPropertyClosureIterator() );
return makeUnique(iterator, propertyName);
}
@@ -1062,18 +1063,18 @@
int cnt = 0;
String propertyName = originalPropertyName;
Set uniqueNames = new HashSet();
-
+
while ( props.hasNext() ) {
Property element = (Property) props.next();
uniqueNames.add( element.getName() );
}
-
- while( uniqueNames.contains(propertyName) ) {
+
+ while( uniqueNames.contains(propertyName) ) {
cnt++;
propertyName = originalPropertyName + "_" + cnt;
}
-
- return propertyName;
+
+ return propertyName;
}
public static void bindCollectionSecondPass(
@@ -1084,15 +1085,15 @@
if(collection.isOneToMany() ) {
OneToMany oneToMany = (OneToMany) collection.getElement();
- PersistentClass persistentClass =
mappings.getClass(oneToMany.getReferencedEntityName() );
-
+ PersistentClass persistentClass =
mappings.getClass(oneToMany.getReferencedEntityName() );
+
if (persistentClass==null) throw new MappingException(
"Association " + collection.getRole() + " references
unmapped class: " + oneToMany.getReferencedEntityName()
);
-
- oneToMany.setAssociatedClass(persistentClass); // Child
+
+ oneToMany.setAssociatedClass(persistentClass); // Child
}
-
+
}
static class JDBCCollectionSecondPass extends CollectionSecondPass {
@@ -1109,9 +1110,9 @@
* @see org.hibernate.cfg.HbmBinder.SecondPass#secondPass(java.util.Map,
java.util.Map)
*/
public void secondPass(Map persistentClasses, Map inheritedMetas) throws
MappingException {
- JDBCBinder.bindCollectionSecondPass(collection, persistentClasses, mappings,
inheritedMetas);
- }
-
+ JDBCBinder.bindCollectionSecondPass(collection, persistentClasses, mappings,
inheritedMetas);
+ }
+
public void doSecondPass(Map persistentClasses) throws MappingException {
Value element = collection.getElement();
DependantValue dep = null;
@@ -1125,8 +1126,8 @@
if(dep!=null) {
dep.setForeignKeyName(oldFkName);
}
-
+
}
}
-
+
}
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java
(rev 0)
+++
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest.java 2009-03-02
14:36:20 UTC (rev 16054)
@@ -0,0 +1,90 @@
+/*******************************************************************************
+ * Copyright (c) 2007-2008 Red Hat, Inc.
+ * Distributed under license by Red Hat, Inc. All rights reserved.
+ * This program is made available under the terms of the
+ * Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at
http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributor:
+ * Red Hat, Inc. - initial API and implementation
+ ******************************************************************************/
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+import java.io.File;
+import java.util.Iterator;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.hibernate.cfg.Configuration;
+import org.hibernate.mapping.Backref;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.tool.NonReflectiveTestCase;
+import org.hibernate.tool.hbm2x.Exporter;
+import org.hibernate.tool.hbm2x.HibernateMappingExporter;
+
+/**
+ * @author Dmitry Geraskov
+ *
+ */
+public class BackrefTest extends NonReflectiveTestCase {
+
+ private String mappingFile = "Car.hbm.xml";
+
+ private Exporter hbmexporter;
+
+ /**
+ * @param name
+ */
+ public BackrefTest(String name) {
+ super(name, "cfg2hbmoutput");
+ }
+
+
+ protected String[] getMappings() {
+ return new String[] {
+ mappingFile
+ };
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ hbmexporter = new HibernateMappingExporter(getCfg(), getOutputDir() );
+ hbmexporter.start();
+ }
+
+ public void testAllFilesExistence() {
+ assertFileAndExists(new File(getOutputDir().getAbsolutePath(), getBaseForMappings() +
"Car.hbm.xml") );
+ assertFileAndExists(new File(getOutputDir().getAbsolutePath(), getBaseForMappings() +
"CarPart.hbm.xml") );
+ }
+
+ public void testBackrefPresent() {
+ Configuration config = getCfg();
+ PersistentClass pc =
config.getClassMapping("org.hibernate.tool.hbm2x.hbm2hbmxml.CarPart");
+ Iterator iterator = pc.getPropertyIterator();
+ boolean hasBackrefs = false;
+ while (iterator.hasNext() && !hasBackrefs) {
+ hasBackrefs = (iterator.next() instanceof Backref);
+ }
+ assertTrue("Class mapping should create Backref for this testcase",
hasBackrefs);
+ }
+
+ public void testReadable() {
+ Configuration cfg = new Configuration();
+
+ cfg.addFile(new File(getOutputDir(), getBaseForMappings() +
"Car.hbm.xml"));
+ cfg.addFile(new File(getOutputDir(), getBaseForMappings() +
"CarPart.hbm.xml"));
+
+ cfg.buildMappings();
+ }
+
+ protected String getBaseForMappings() {
+ return "org/hibernate/tool/hbm2x/hbm2hbmxml/";
+ }
+
+ public static Test suite() {
+ return new TestSuite(BackrefTest.class);
+ }
+
+}
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml
(rev 0)
+++
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.hbm.xml 2009-03-02
14:36:20 UTC (rev 16054)
@@ -0,0 +1,26 @@
+<?xml version="1.0"?>
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<hibernate-mapping package="org.hibernate.tool.hbm2x.hbm2hbmxml">
+
+ <class name="Car" lazy="false" node="car">
+ <id name="id" node="@id" type="long">
+ <generator class="increment"/>
+ </id>
+ <property name="model" type="string"
node="model"/>
+ <set name="carParts" node="." cascade="all">
+ <key column="car" not-null="true"/>
+ <one-to-many class="CarPart" node="carPart"
embed-xml="false"/>
+ </set>
+ </class>
+
+ <class name="CarPart" node="carPart">
+ <id name="id" node="@id" type="long">
+ <generator class="increment"/>
+ </id>
+ <property name="partName" type="string"
node="partName"/>
+ </class>
+
+</hibernate-mapping>
\ No newline at end of file
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java
(rev 0)
+++
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Car.java 2009-03-02
14:36:20 UTC (rev 16054)
@@ -0,0 +1,45 @@
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * @author Paco Hern�ndez
+ */
+public class Car implements java.io.Serializable {
+
+ private long id;
+ private String model;
+ private Set carParts = new HashSet();
+
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the model.
+ */
+ public String getModel() {
+ return model;
+ }
+ /**
+ * @param model The model to set.
+ */
+ public void setModel(String model) {
+ this.model = model;
+ }
+ public Set getCarParts() {
+ return carParts;
+ }
+ public void setCarParts(Set carParts) {
+ this.carParts = carParts;
+ }
+}
Added:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java
(rev 0)
+++
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/CarPart.java 2009-03-02
14:36:20 UTC (rev 16054)
@@ -0,0 +1,35 @@
+package org.hibernate.tool.hbm2x.hbm2hbmxml;
+
+/**
+ * @author Paco Hern�ndez
+ */
+public class CarPart implements java.io.Serializable {
+
+ private long id;
+ private String partName;
+
+ /**
+ * @return Returns the id.
+ */
+ public long getId() {
+ return id;
+ }
+ /**
+ * @param id The id to set.
+ */
+ public void setId(long id) {
+ this.id = id;
+ }
+ /**
+ * @return Returns the typeName.
+ */
+ public String getPartName() {
+ return partName;
+ }
+ /**
+ * @param typeName The typeName to set.
+ */
+ public void setPartName(String typeName) {
+ this.partName = typeName;
+ }
+}
Modified:
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java
===================================================================
---
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java 2009-03-02
10:31:56 UTC (rev 16053)
+++
branches/Branch_3_2/HibernateExt/tools/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmAllTests.java 2009-03-02
14:36:20 UTC (rev 16054)
@@ -18,6 +18,7 @@
suite.addTest(OneToOneTest.suite());
suite.addTest(InheritanceTest.suite());
suite.addTest(SetElementTest.suite());
+ suite.addTest(BackrefTest.suite());
//$JUnit-END$
return suite;
}