Hibernate DDL is generating wrong FK constraints when we have MappedSupperclass containing ManyToMany relation and if we have more then 2 classes extending it.(doesn't work for 2,3,4 .. works for 1 or the first extending entity only )
I have a MappedSupperclass
@MappedSuperclass
public abstract class AbstractFilteredEntityModel {
...
@ManyToMany(fetch = FetchType.LAZY, targetEntity = AbstractFilterModel.class, cascade = { CascadeType.ALL})
@JoinTable(name="entity_filters", joinColumns = @JoinColumn( name="entity_pk"), inverseJoinColumns = @JoinColumn( name="filter_pk"))
private Collection<AbstractFilterModel> filters;
}
And I have several classes that extend this class which are Entities ( more then 1 )
All of them look like (you must have more then 1 ! ) :
@Entity(name = AbstractPageModel.NAME)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = AbstractPageModel.NAME, uniqueConstraints = { @UniqueConstraint(columnNames = { "pk", "id" }) }, indexes = { @Index(columnList = "id")})
public class AbstractPageModel extends AbstractFilteredEntityModel {
}
The problem is the SQL DDL script that is generated by org.hibernate.cfg.Configuration#generateSchemaCreationScript is using the same FK name for each entity after the second one. So the generated SQL script looks like this :
alter table entity_filters
add constraint FK_f3947dp1iy1bp0i2nfbkpvuom
foreign key (filter_pk)
references abstract_filter (pk);
alter table entity_filters
add constraint FK_8b6xl4emqmow8hikaf4hgx9xn
foreign key (entity_pk)
references abstract_page (pk);
alter table entity_filters
add constraint FK_8b6xl4emqmow8hikaf4hgx9xn
foreign key (entity_pk)
references tax (pk);
alter table entity_filters
add constraint FK_8b6xl4emqmow8hikaf4hgx9xn
foreign key (entity_pk)
references price (pk);
alter table entity_filters
add constraint FK_8b6xl4emqmow8hikaf4hgx9xn
foreign key (entity_pk)
references stock_level (pk);
As you can notice.. the first one (the abstract one is ok).. the second one is also ok.. but each other entity that extends the mapped super class have the same constraint name which is invalid.
I've tried to debug the problem and saw that it in generateSchemaCreationScript method in org.hibernate.Configuation class contains the following snippet :
while ( subIter.hasNext() ) {
ForeignKey fk = (ForeignKey) subIter.next();
if ( fk.isPhysicalConstraint() ) {
script.add(
fk.sqlCreateString(
dialect, mapping,
defaultCatalog,
defaultSchema
)
);
}
}
And here this "fk" ... fk.getName() is the same for each FK... while it should be different because fk.getName() is used inside sqlCreateString method to generate the actual SQL. I believe something is wrong when TableMappings are created.
|