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.id.IdentifierGeneratorFactory;
import org.hibernate.type.Type;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class FunctionIdGeneratorimplements IdentifierGenerator, Configurable {
private static final Log log = LogFactory.getLog(FunctionIdGenerator.class);
private String entityName;
private Class returnClass;
String IdGeneratorFunction = null;
public void configure(Type type, Properties params, Dialect dialect)
throws MappingException {
entityName = params.getProperty(ENTITY_NAME);
if (entityName==null) {
throw new MappingException("no entity name");
}
returnClass = type.getReturnedClass();
IdGeneratorFunction = params.getProperty("function");
}
public Serializable generate(SessionImplementor session, Object obj)
throws HibernateException {
final Serializable id = session.getEntityPersister( entityName, obj ) .getIdentifier( obj, session.getEntityMode() );
boolean idIsNull = (id==null);
boolean idIsZero = false;
try {
if (id instanceof Long) {
idIsZero = (((Long)id).longValue() == 0);
}
else if (id instanceof Integer) {
idIsZero = (((Integer)id).intValue() == 0);
}
else if (id instanceof Short) {
idIsZero = (((Short)id).intValue() == 0);
}
}catch (Exception e) {
idIsZero = false;
}
if ((idIsNull) || (idIsZero)){
String sql = "{ ? = call "+IdGeneratorFunction+" }";
try {
CallableStatement st = session.getBatcher().prepareCallableStatement(sql);
st.registerOutParameter(1, java.sql.Types.NUMERIC);
try {
st.executeUpdate();
Serializable result = IdentifierGeneratorFactory.createNumber( st.getLong(1), returnClass );
//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 caat value ",
sql
);
}
} else {
return id;
}
}
}
|