I'll post my solution because surfing the net I could not find anything relevant to solve my issue.
My application uses the Spring Framework and the Hibernate session factory is a bean defined as
Code:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
...all properties...
</bean>
To define an index I need to know when the database schema is completely generated by hibernate. So I find in LocalSessionfactoryBean the method afterSessionFactoryCreation() which is called after the SessionFactory has been successfully created.
What I did is to extends org.springframework.orm.hibernate3.LocalSessionFactoryBean and override its afterSessionFactoryCreation() method:
Code:
public class MyLocalSessionFactoryBean extends org.springframework.orm.hibernate3.LocalSessionFactoryBean {
private static final Log log = LogFactory.getLog(MyLocalSessionFactoryBean.class);
/**
* {@inheritDoc}
* @see org.springframework.orm.hibernate3.LocalSessionFactoryBean#afterSessionFactoryCreation()
*/
@Override
protected void afterSessionFactoryCreation() throws Exception {
super.afterSessionFactoryCreation();
try {
log.debug(this + " now getting session to execute sql for partial index creation");
Session s = this.getSessionFactory().openSession();
Query indexCreate = s.createSQLQuery("CREATE INDEX strvalues_idx ON myClass (value) WHERE length(value) < 512");
log.debug("And the create statement is: " + indexCreate.getQueryString());
indexCreate.executeUpdate();
s.close();
log.debug("INDEX CREATED");
} catch (org.hibernate.exception.SQLGrammarException e) {
/*
* this exception if there are error with the sql. I expect this exception if the index already exists. In
* that case the inner exception will be a org.postgresql.util.PSQLException: ERROR: relation
* "strvalues_idx" already exists What to do in the case: nothing! if the index already exists it already
* exists!
*/
log.debug("The index already exists");
}
}
}
Then it is enough to use that new class as the sessionFactory bean class, so that the index is created if it does not exist yet:
Code:
<bean id="sessionFactory" class="MyLocalSessionFactoryBean">
...all properties...
</bean>
Please share your comments with this solution if you wish.
Alessia