bonjour j'utilise Hibernate 2.1.6 et je bloque sur un prb concernant le
genérateur d'id de Hibernate. Ma dans ma base Oracle 9i, le DBA a
créé un trigger qui créé les identifiants de ma table. J'ai cherché dans
la doc comment faire pour paramétrer le mapping afin de récupérer
ce qui est généré par le trigger. Je n'ai rien trouvé.
Donc j'ai crée une classe pour faire le travail. Mais manque de chance.
Je me rends compte que mon classe s'éxécute avant le trigger. Donc je
récupére le n-1 identifiants. Merci de votre aide :
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.dialect.Dialect;
import net.sf.hibernate.engine.SessionImplementor;
import net.sf.hibernate.id.Configurable;
import net.sf.hibernate.id.IdentifierGenerator;
import net.sf.hibernate.id.PersistentIdentifierGenerator;
import net.sf.hibernate.type.Type;
public class TriggerGenerator implements IdentifierGenerator, Configurable {
private long next;
private String sql = null;
private Class returnClass = null;
/**
*
* @see net.sf.hibernate.id.IdentifierGenerator#generate(net.sf.hibernate.engine.SessionImplementor, java.lang.Object)
*/
public Serializable generate(SessionImplementor session, Object object) throws SQLException, HibernateException {
if (sql!=null) {
getNext( session.connection());
}
return new Long(next);
}
/**
*
*
* @see net.sf.hibernate.id.Configurable#configure(net.sf.hibernate.type.Type, java.util.Properties, net.sf.hibernate.dialect.Dialect)
*/
public void configure(Type type, Properties params, Dialect d) throws MappingException {
String table = params.getProperty("table");
if (table==null) table = params.getProperty(PersistentIdentifierGenerator.TABLE);
String column = params.getProperty("column");
if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK);
String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
returnClass = type.getReturnedClass();
sql = "select max(" + column + ") from " + ( schema==null ? table : schema + '.' + table );
}
/**
*
* @param conn
* @throws SQLException
*/
private void getNext(Connection conn) throws SQLException {
ResultSet rs = null;
PreparedStatement st = conn.prepareStatement(sql);
try {
rs = st.executeQuery();
if ( rs.next() ) {
next = rs.getLong(1);
}
else {
throw new SQLException("Impossible de récupérer l'identifiant généré par le trigger");
}
sql=null;
}
finally {
if (rs!=null) rs.close();
st.close();
}
}
}
|