Hibernate (the version currently in use is 3.2) provides a variety of ways to generate primary keys.
However, the current generation of such a variety of methods may not be able to meet our requirements.
Increment, for example, can be handy in a hibernate instance, but not in the cluster.
Again such as identity, sequence, native is provided by the Data Bureau of the primary key generation way, often not we need, and in the program across the database also reflects deficiencies.
There is also a generation based on the algorithm generated by the primary key is basically a string.
We now need a way to build: use long as the primary key type, automatically increase, support the cluster.
Then we need to customize one of our primary key generators to be implemented.
Implementation code:
package hibernate;
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 Org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
Import org.hibernate.MappingException;
import Org.hibernate.dialect.Dialect;
import Org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import Org.hibernate.id.IdentifierGenerator;
import Org.hibernate.id.PersistentIdentifierGenerator;
import Org.hibernate.type.Type;
public class Incrementgenerator implements Identifiergenerator, configurable {
private static Final log = Logfactory.getlog (Incrementgenerator.class);
private Long Next;
private String SQL;
public Serializable Generate (Sessionimplementor session, object)
throws Hibernateexception {
if (sql!=null) {
GetNext (Session.connection ());
}
return next;
}
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);
sql = "Select Max (" +column + ") from" + (schema==null?) Table:schema + '. ' + table);
log.info (SQL);
}
private void GetNext (Connection conn) throws Hibernateexception {
try {
PreparedStatement st = conn.preparestatement (SQL);
ResultSet rs = St.executequery ();
if (Rs.next ()) {
next = Rs.getlong (1) + 1;
}
else {
next = 1l;
}
}catch (SQLException e)
{
throw new Hibernateexception (e);
}
finally {
try{
Conn.close ();
}catch (SQLException e)
{
throw new Hibernateexception (e);
}
}
}
}
Configuration:
The ID is configured as follows in the corresponding HBM file:
<id name="id" type="long" column="id" >
<generator class="hibernate.IncrementGenerator" />
</id>