// create relation tables
JDBCAbstractCMRFieldBridge[] cmrFields = entity.getCMRFields();
for (int i = 0; i < cmrFields.length; ++i) {
JDBCAbstractCMRFieldBridge cmrField = cmrFields[i];
JDBCRelationMetaData relationMetaData = cmrField.getMetaData().getRelationMetaData();
DataSource dataSource = manager.getDataSource(relationMetaData.getDataSourceName());
// if the table for the related entity has been created
final EntityBridge relatedEntity = cmrField.getRelatedEntity();
if (relationMetaData.isTableMappingStyle() && manager.hasCreateTable(relatedEntity.getEntityName())) {
boolean relTableExisted = SQLUtil.tableExists(cmrField.getQualifiedTableName(), entity.getDataSource());
if (relTableExisted) {
if (relationMetaData.getAlterTable()) {
ArrayList oldNames = SQLUtil.getOldColumns(cmrField.getQualifiedTableName(), dataSource).getColumnNames();
ArrayList newNames = new ArrayList();
JDBCFieldBridge[] leftKeys = cmrField.getTableKeyFields();
JDBCFieldBridge[] rightKeys = cmrField.getRelatedCMRField().getTableKeyFields();
JDBCFieldBridge[] fields = new JDBCFieldBridge[leftKeys.length + rightKeys.length];
System.arraycopy(leftKeys, 0, fields, 0, leftKeys.length);
System.arraycopy(rightKeys, 0, fields, leftKeys.length, rightKeys.length);
// have to append field names to leftKeys, rightKeys...
boolean different = false;
for (int j = 0; j < fields.length; j++) {
JDBCFieldBridge field = fields[j];
String name = field.getJDBCType().getColumnNames()[0].toUpperCase();
newNames.add(name);
if (!oldNames.contains(name)) {
different = true;
break;
}
} // for int j;
if (!different) {
Iterator it = oldNames.iterator();
while (it.hasNext()) {
String name = (String) (it.next());
if (!newNames.contains(name)) {
different = true;
break;
}
}
}
if (different) {
// only log, don't drop table is this can cause data loss
log.error("CMR table structure is incorrect for " + cmrField.getQualifiedTableName());
//SQLUtil.dropTable(entity.getDataSource(), cmrField.getQualifiedTableName());
}
} // if alter-table
} // if existed
// create the relation table
if (relationMetaData.isTableMappingStyle() && !relationMetaData.isTableCreated()) {
if (relationMetaData.getCreateTable()) {
createTable(dataSource, cmrField.getQualifiedTableName(),
getRelationCreateTableSQL(cmrField, dataSource));
} else {
log.debug("Relation table not created as requested: " + cmrField.getQualifiedTableName());
}
// create Indices if needed
createCMRIndex(dataSource, cmrField);
if (relationMetaData.getCreateTable()) {
issuePostCreateSQL(dataSource,
relationMetaData.getDefaultTablePostCreateCmd(),
cmrField.getQualifiedTableName());
}
}
}
}