package org.hibernate.cfg;
import java.util.Map;
import org.hibernate.AnnotationException;
import org.hibernate.MappingException;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Table;
public class IndexOrUniqueKeySecondPass implements SecondPass {
private Table table;
private final String indexName;
private final String[] columns;
private final Mappings mappings;
private final Ejb3Column column;
private final boolean unique;
public IndexOrUniqueKeySecondPass(Table table, String indexName, String[] columns, Mappings mappings) {
this.table = table;
this.indexName = indexName;
this.columns = columns;
this.mappings = mappings;
this.column = null;
this.unique = false;
}
public IndexOrUniqueKeySecondPass(String indexName, Ejb3Column column, Mappings mappings) {
this( indexName, column, mappings, false );
}
public IndexOrUniqueKeySecondPass(String indexName, Ejb3Column column, Mappings mappings, boolean unique) {
this.indexName = indexName;
this.column = column;
this.columns = null;
this.mappings = mappings;
this.unique = unique;
}
@Override
public void doSecondPass(Map persistentClasses) throws MappingException {
if ( columns != null ) {
for ( int i = 0; i < columns.length; i++ ) {
addConstraintToColumn( columns[i] );
}
}
if ( column != null ) {
this.table = column.getTable();
addConstraintToColumn( mappings.getLogicalColumnName( column.getMappingColumn().getQuotedName(), table ) );
}
}
private void addConstraintToColumn(final String columnName ) {
Column column = table.getColumn(
new Column(
mappings.getPhysicalColumnName( columnName, table )
)
);
if ( column == null ) {
throw new AnnotationException(
"@Index references a unknown column: " + columnName
);
}
if ( unique )
table.getOrCreateUniqueKey( indexName ).addColumn( column );
else
table.getOrCreateIndex( indexName ).addColumn( column );
}
}