I have made a posible solution for id generation with triggers. I'm using Oracle 10g database, but this solution is quite simple in order to apply to other databases: simlpy use this class, transform trigger to a database function and map id generator class like this form:
Mapping
======
<id name="Id" column="ID" type="java.lang.Long" >
<generator
class="com.isoco.caatv.persistence.hibernate.FunctionIdGenerator" >
<param name="function">MyFunctionWasPrevATrigger</param>
</generator>
</id>
FunctionIdGenerator.java
=================
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.exception.JDBCExceptionHelper;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FunctionIdGenerator implements IdentifierGenerator, Configurable {
private static final Log log =
LogFactory.getLog(FunctionIdGenerator.class);
String IdGeneratorFunction = null;
public void configure(Type type, Properties params, Dialect dialect)
throws MappingException {
IdGeneratorFunction = params.getProperty("function");
}
public Serializable generate(SessionImplementor session,
Object obj)
throws HibernateException {
String sql = "{ ? = call "+IdGeneratorFunction+" }";
try {
CallableStatement st =
session.getBatcher().prepareCallableStatement(sql);
st.registerOutParameter(1, java.sql.Types.NUMERIC);
try {
st.executeUpdate();
Serializable result = new Long ( st.getLong(1) );
if ( log.isDebugEnabled() ) {
log.debug("Caat identifier generated: " + result);
}
return result;
}
finally {
session.getBatcher().closeStatement(st);
}
}
catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(
session.getFactory().getSQLExceptionConverter(),
sqle,
"could not get next function value ",
sql
);
}
}
}
[/b]
|