Excluding Hibernate entities from auto-generation

Today I had to do something completely new with Hibernate, within the scope of a unit test. I had a group of entities and wanted to exclude one of them from the schema auto-generation (hibernate.hbm2ddl.auto=create).

After spending a couple of hours trying out different things and reading Stackoverflow answers, I hit jackpot with this cool solution:

  • implement the SchemaFilterProvider and the SchemaFilter interfaces
  • in the SchemaFilter implementation, add an if condition to includeTable so that it returns false for the table that you don’t want to create
  • add hibernate.properties to the classpath and define hibernate.hbm2ddl.schema_filter_provider to point to the SchemaFilterProvider implementation

What follows is an example of an implementation. In my case, I want to exclude all entities that would create a table that has namespace in its name.

hibernate.hbm2ddl.schema_filter_provider=com.horiaconstantin.Provider
view raw hibernate.properties hosted with ❤ by GitHub
package com.horiaconstantin;
import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.boot.model.relational.Sequence;
import org.hibernate.mapping.Table;
import org.hibernate.tool.schema.spi.SchemaFilter;
import org.hibernate.tool.schema.spi.SchemaFilterProvider;
public class Provider implements SchemaFilterProvider {
@Override
public SchemaFilter getCreateFilter() {
return MySchemaFilter.INSTANCE;
}
@Override
public SchemaFilter getDropFilter() {
return MySchemaFilter.INSTANCE;
}
@Override
public SchemaFilter getMigrateFilter() {
return MySchemaFilter.INSTANCE;
}
@Override
public SchemaFilter getValidateFilter() {
return MySchemaFilter.INSTANCE;
}
}
class MySchemaFilter implements SchemaFilter {
public static final MySchemaFilter INSTANCE = new MySchemaFilter();
@Override
public boolean includeNamespace(Namespace namespace) {
return true;
}
@Override
public boolean includeTable(Table table) {
if (table.getName().toLowerCase().contains("namespace")){
return false;
}
return true;
}
@Override
public boolean includeSequence(Sequence sequence) {
return true;
}
}
view raw Provider.java hosted with ❤ by GitHub

Reference: https://stackoverflow.com/questions/6212144/how-to-disable-schema-validation-in-hibernate-for-certain-entities

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.