Hibernate自定义主键

前言

  1. 背景:Hibernate是靠对象标识OID来区分对象的,Hibernate自带的标识(OID)生成器不足以满足需求,用户需要定义自己的对象标识生成器。
  2. Hibernate(3.0)提供的标识生成器扩展相关接口:org.hibernate.id.IdentifierGenerator和org.hibernate.id.Configurable
  3. 参考资料:Hibernate官方网站的NativeHiloGenerator 的实现。

方法与原理

  1. 用户实现指定标识生成器扩展接口IdentifierGenerator。 org.hibernate.id.IdentifierGenerator是Hibernate提供的对象标识生成器的扩展接口,另外,如果需要在配置文件中加载一些用户定义的参数,则需要同时实现接口org.hibernate.id.Configurable。
  2. 在ORMapping文件中设定使用自定义的OID生成器。
    <id name="uid" column="id" type="long">
       <generator class="gocom.identifier.DateSeqGenerator">
          <param name="length">4</param>
       </generator>
    </id>
    
    
    
    
  3. Hibernate 根据2中的配置,从ClassPath下装载扩展的Java Class,然后实例化该类,并调用其接口方法生成ID。Hibernate的主键生成器扩展是通过一个工厂类(设计模 式)IdentifierGeneratorFactory实现的。其实现原理可以参看如下部分代码,
    public final class IdentifierGeneratorFactory {
    	private static final HashMap GENERATORS = new HashMap();
    
    	public static final String SHORT_CIRCUIT_INDICATOR = new String();
    	public static final String POST_INSERT_INDICATOR = new String();
    
    	static {
    		GENERATORS.put("uuid", UUIDHexGenerator.class);
    		GENERATORS.put("hilo", TableHiLoGenerator.class);
    		GENERATORS.put("assigned", Assigned.class);
    		GENERATORS.put("identity", IdentityGenerator.class);
    		GENERATORS.put("select", SelectGenerator.class);
    		GENERATORS.put("sequence", SequenceGenerator.class);
    		GENERATORS.put("seqhilo", SequenceHiLoGenerator.class);
    		GENERATORS.put("increment", IncrementGenerator.class);
    		GENERATORS.put("foreign", ForeignGenerator.class);
    		GENERATORS.put("guid", GUIDGenerator.class);
    		GENERATORS.put("uuid.hex", UUIDHexGenerator.class); //uuid.hex is deprecated
    	}
    
    	public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect) 
    	throws MappingException {
    		try {
    			Class clazz = getIdentifierGeneratorClass( strategy, dialect );
    			IdentifierGenerator idgen = (IdentifierGenerator) clazz.newInstance();
    			if (idgen instanceof Configurable) ( (Configurable) idgen).configure(type, params, dialect);
    			return idgen;
    		}
    		catch (Exception e) {
    			throw new MappingException("could not instantiate id generator", e);
    		}
    	}
    
    	public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
    		Class clazz = (Class) GENERATORS.get(strategy);
    		if ( "native".equals(strategy) ) clazz = dialect.getNativeIdentifierGeneratorClass();
    		try {
    			if (clazz==null) clazz = ReflectHelper.classForName(strategy);
    		}
    		catch (ClassNotFoundException e) {
    			throw new MappingException("could not interpret id generator strategy: " + strategy);
    		}
    		return clazz;
    	}
    
    	private IdentifierGeneratorFactory() {} //cannot be instantiated
    
    }
    
    
    

相关的接口

  这里我们只介绍最基本的两个接口org.hibernate.id.IdentifierGenerator和org.hibernate.id.Configurable,其接口定义如下,

IdentifierGenerator接口定义:


package org.hibernate.id;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import java.io.Serializable;

public interface IdentifierGenerator {

    /**
     * The configuration parameter holding the entity name
     */
    public static final String ENTITY_NAME = "entity_name";
    
	/**
	 * Generate a new identifier.
	 * @param session
	 * @param object the entity or toplevel collection for which the id is being generated
	 *
	 * @return a new identifier
	 * @throws HibernateException
	 */
	public Serializable generate(SessionImplementor session, Object object) 
	throws HibernateException;

}


Configurable接口定义如下:


package org.hibernate.id;
import java.util.Properties;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.type.Type;

public interface Configurable {
	/**
	 * Configure this instance, given the value of parameters
	 * specified by the user as <param>

 elements.
	 * This method is called just once, following instantiation.
	 *
	 * @param params param values, keyed by parameter name
	 */
	public void configure(Type type, Properties params, Dialect d) throws MappingException;
}


代码示例

  这个示例里我们扩展的ID标识的规则是日期加当天的流水号,流水号的位数由输入的参数决定,本例中限定流水号的位数是4位。目标生成的OID例如:200603150099,代码如下

扩展标识生成器类 DateSeqGenerator:

package gocom.identifier;

import java.io.Serializable;
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.type.Type;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateSeqGenerator implements IdentifierGenerator, 
                                            Configurable {
  // logger
  private static final Log log = LogFactory.getLog(DateSeqGenerator.class);
    
  // reference to the underlying generator to which we delegate the work
  private String currentDate = "";
    
  //上次生成标识的日期前缀
  private long day;
    
  //下一个Sequence值
  private long next;
    
  //末位序号的位数限制
  private int length = 4;
    
  //从数据库获取当前最大标识的Sql语句
  private String sql;
 
  //标识返回值的JAVA类别
  private Class returnClass;
    
  /**
   * Construct a new DateSeqGenerator
   */
  public DateSeqGenerator() {
        super();
  }
    
  /* (non-Javadoc)  

   

* @see org.hibernate.id.IdentifierGenerator#generate(org.hibernate.engine.SessionImplementor, java.lang.Object)
   */
  public Serializable generate(SessionImplementor session, Object object)
            throws SQLException, HibernateException   

  {
    if (sql!=null) {
      getNext( session );
    }
  
    long currentDay = getCurrentDay();
    if(currentDay != day){
      day = currentDay;
      next = 1l;
    }
    return IdentifierGeneratorFactory.createNumber(day * Math.pow(10l,length) + (next++), returnClass);
  }


    /* (non-Javadoc)
     * @see org.hibernate.id.Configurable#configure(org.hibernate.type.Type, java.util.Properties, org.hibernate.dialect.Dialect)
     */
    public void configure(Type type, Properties params, Dialect dialect)
            throws MappingException 
    {
    String tableList = params.getProperty("tables");
    if (tableList==null) tableList = params.getProperty(PersistentIdentifierGenerator.TABLES);
    String[] tables = StringHelper.split(", ", tableList);
    String column = params.getProperty("column");
    if (column==null) column = params.getProperty(PersistentIdentifierGenerator.PK);
    String numLength = params.getProperty("length");
    if(numLength == null) 
      length = 4;
    else
      length = Integer.parseInt(numLength);
  
    String schema = params.getProperty(PersistentIdentifierGenerator.SCHEMA);
    String catalog = params.getProperty(PersistentIdentifierGenerator.CATALOG);
    returnClass = type.getReturnedClass();
  
    StringBuffer buf = new StringBuffer();
    for ( int i=0; i<tables.length; i++ ) {
      if (tables.length>1) {
        buf.append("select ").append(column).append(" from ");
      }
      buf.append( Table.qualify(catalog, schema, tables[i], d.getSchemaSeparator() ) );
      if ( i<tables.length-1) buf.append(" union ");
    }
    if (tables.length>1) {
      buf.insert(0, "( ").append(" ) ids_");
      column = "ids_." + column;
    }
  
    sql = "select max(" + column + ") from " + buf.toString();
  }
    
  /**
   * 从数据库检索已有数据标识的最大值
  
   * @param session
   * 
   * @return 
  */
  //从数据库获取已有数据的最大ID标识,确定下一标识的值
  private void getNext( SessionImplementor session ) {
  Connection conn = session.connection();
  log.debug("fetching initial value: " + sql);
  
  try {
    PersistentIdentifierGenerator.SQL.debug(sql);
    PreparedStatement st = conn.prepareStatement(sql);
    ResultSet rs = null;
    try {
      rs = st.executeQuery();
      if ( rs.next() ) {
        next = rs.getLong(1);
        if ( rs.wasNull()) 
          next = 1l;
        else{
          day = Long.parseLong(next.substring(0,8)) + 1;     }
          next = Long.parseLong((next + "").substring(8));
        }
      else {
        next = 1l;
      }
      sql=null;
      log.debug("first free id: " + next);
    }
    finally {
      if (rs!=null) rs.close();
        st.close();
    }
  }
  catch (SQLException sqle) {
    throw JDBCExceptionHelper.convert(
           session.getFactory().getSQLExceptionConverter(),
           sqle,
           "could not fetch initial value",
           sql
      );
    }
  }
 
  /**
   * 从数据库服务器获取当前日期
   * 
   * @return long 数据库当前日期,日期格式为'yyyymmdd'
  */
  private long getCurrentDay(){
    String cDate = null;
    /**此部分代码省略**/
    /** 从数据库获取当前日期,返回格式为'yyyymmdd',“20060316”**/
    return cDate;
  }
}




附:

Hibernate主键生成方式(转)

关键字: hibernate 1) assigned
主键由外部程序负责生成,无需Hibernate参与。

2) hilo
通过hi/lo 算法实现的主键生成机制,需要额外的数据库表保存主
键生成历史状态。

3) seqhilo
与hilo 类似,通过hi/lo 算法实现的主键生成机制,只是主键历史
状态保存在Sequence中,适用于支持Sequence的数据库,如Oracle。

4) increment
主键按数值顺序递增。此方式的实现机制为在当前应用实例中维持
一个变量,以保存着当前的最大值,之后每次需要生成主键的时候
将此值加1作为主键。
这种方式可能产生的问题是:如果当前有多个实例访问同一个数据
库,那么由于各个实例各自维护主键状态,不同实例可能生成同样
的主键,从而造成主键重复异常。因此,如果同一数据库有多个实
例访问,此方式必须避免使用。

5) identity
采用数据库提供的主键生成机制。如DB2、SQL Server、MySQL
中的主键生成机制。

6) sequence
采用数据库提供的sequence 机制生成主键。如Oralce 中的
Sequence。

7) native
由Hibernate根据底层数据库自行判断采用identity、hilo、sequence
其中一种作为主键生成方式。

8) uuid.hex
由Hibernate基于128 位唯一值产生算法生成16 进制数值(编码后
以长度32 的字符串表示)作为主键。

9) uuid.string
与uuid.hex 类似,只是生成的主键未进行编码(长度16)。在某些
数据库中可能出现问题(如PostgreSQL)。

10) foreign
使用外部表的字段作为主键。
一般而言,利用uuid.hex方式生成主键将提供最好的性能和数据库平台适
应性。

另外由于常用的数据库,如Oracle、DB2、SQLServer、MySql 等,都提
供了易用的主键生成机制(Auto-Increase 字段或者Sequence)。我们可以在数
据库提供的主键生成机制上,采用generator-class=native的主键生成方式。
不过值得注意的是,一些数据库提供的主键生成机制在效率上未必最佳,
大量并发insert数据时可能会引起表之间的互锁。
数据库提供的主键生成机制,往往是通过在一个内部表中保存当前主键状
态(如对于自增型主键而言,此内部表中就维护着当前的最大值和递增量),
之后每次插入数据会读取这个最大值,然后加上递增量作为新记录的主键,之
后再把这个新的最大值更新回内部表中,这样,一次Insert操作可能导致数据
库内部多次表读写操作,同时伴随的还有数据的加锁解锁操作,这对性能产生
了较大影响。
因此,对于并发Insert要求较高的系统,推荐采用uuid.hex 作为主键生成
机制。


                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值