Monday, July 25, 2005

Postgresql sequences + CJDBC + Hibernate

CJDBC has a problem understanding PostgreSQL sequences. This program solves that problem.
//$Id: CJDBCPostgreSQLDialect.java,v 1.22 2004/08/08 08:23:16 oneovthafew Exp $
package net.sf.hibernate.dialect;

import java.sql.Types;

import net.sf.hibernate.Hibernate;
import net.sf.hibernate.cfg.Environment;

/*************************************************
 *** As of CJDBC 1.1 this file is necessary for Postgresql sequences to
 *** work withCJDBC and Hibernate.
 *** Apparently, CJDBC does not like select statements of the type:
 ***            select nextval('seq_name');
 ***
 *** So, to get around this problem whenever Hibernate requests a
 *** nextval for a Postgres sequence, we have to return:
 ***            {call nextval('seq_name')}
 *** which is something that CJDBC understands and accepts.
 *********************************************/
import net.sf.hibernate.dialect.PostgreSQLDialect;

public class CJDBCPostgreSQLDialect extends PostgreSQLDialect
{
    public String getSequenceNextValString(String sequenceName)
    { return "{call nextval('"+sequenceName+"')}"; }
}
Compile this file and add it in hibernate2.jar at the path:

net/sf/hibernate/dialect


Repackage the jar and drop it whever you have kept the original hibernate.jar.

Remember to specify this dialect in hibernate.cfg.xml:

<propertyname="dialect">
    net.sf.hibernate.dialect.CJDBCPostgreSQLDialect
</property>

Powered by Blogger