Hibernate的ID生成原理

来源:http://www.cnblogs.com/firstdream/archive/2012/04/22/2464681.html

 

支持的策略包括:uuid, hilo, assigned, identity, select, sequence, seqhilo, increment, foreign, guid, uuid.hex, sequence-identity.

对应这些策略, 可以在org.hibernate.id包下找到, 其中有一个IdentifierGeneratorFactory类用于根据实体类的配置(hbm文件的<id>元素或@Id,@GeneratedValue注解)来创建相应的策略.

public final class IdentifierGeneratorFactory {
... //注册所有支持的ID生成策略
private static final HashMap GENERATORS = new HashMap();
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
   GENERATORS.put( "sequence-identity", SequenceIdentityGenerator.class );
}
...
public static IdentifierGenerator create(String strategy, Type type, Properties params, Dialect dialect)
    throws MappingException {
   try {
    Class clazz = getIdentifierGeneratorClass( strategy, dialect );
...
}

public static Class getIdentifierGeneratorClass(String strategy, Dialect dialect) {
   Class clazz = ( Class ) GENERATORS.get( strategy );
...
}
}
显然create()方法是用于创建ID生成器的, 而且用到了参数strategy和dialect. Hibernate在初始化SessionFactory的时候就会准备这些ID生成器. 见以下代码

SessionFactoryImpl(){
...
   Iterator classes = cfg.getClassMappings();
   while ( classes.hasNext() ) {
    PersistentClass model = (PersistentClass) classes.next();
    if ( !model.isInherited() ) {
     IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
       settings.getDialect(),
            settings.getDefaultCatalogName(),
            settings.getDefaultSchemaName(),
            (RootClass) model
      );
     identifierGenerators.put( model.getEntityName(), generator );
    }
   }

model.getIdentifier().createIdentifierGenerator() 最终会引用到
return IdentifierGeneratorFactory.create(
     identifierGeneratorStrategy,
     getType(),
     params,
     dialect
    );

看来SessionFactory做了太多的工作. 为了能对这么多中ID生成策略有最直观的了解, 下面给出一个各种ID策略的类关系图.

看Hibernate源码之 ID Generator - wolfgangkiefer - wolfgangkiefer的博客
 

该图分为两部分, 蓝色先左边的ID生成器是不需要借助数据库, 采用本地算法生成的, 而右边的ID生成器则需要借助数据库提供的ID生成能力.

最主要的接口有4个, 图中用蓝色标出.
* IdentifierGenerator: ID生成器接口, 只有一个generate方法, 返回生成的ID.
* PostInsertIdentifierGenerator: 针对MySQL, MSSQL这类能为主键设置自动增长的ID生成器
* PersistentIdentifierGenerator: 针对需要访问DB来生成ID的生成器, 比如GUID.
* Configurable: 用于读取配置信息

具体每个类如何处理:
1) uuid: 是采用128位的算法生成惟一值,支持大部分的数据库
   public Serializable generate(SessionImplementor session, Object obj) {
   return new StringBuffer(36)
    .append( format( getIP() ) ).append(sep)
    .append( format( getJVM() ) ).append(sep)
    .append( format( getHiTime() ) ).append(sep)
    .append( format( getLoTime() ) ).append(sep)
    .append( format( getCount() ) ) //注: 每次加1, JVM内唯一, 通过synchronized来保证实现
    .toString();
}
protected String format(int intval) {
   String formatted = Integer.toHexString(intval);
   StringBuffer buf = new StringBuffer("00000000");
   buf.replace( 8-formatted.length(), 8, formatted );
   return buf.toString();
}
protected String format(short shortval) {
   String formatted = Integer.toHexString(shortval);
   StringBuffer buf = new StringBuffer("0000");
   buf.replace( 4-formatted.length(), 4, formatted );
   return buf.toString();

2)GUID: 通过使用数据库本身的uuid算法来实现
public class GUIDGenerator implements IdentifierGenerator {
   public Serializable generate(SessionImplementor session, Object obj) 
   throws HibernateException {
       final String sql = session.getFactory().getDialect().getSelectGUIDString();
   ...
}
假如getDialect()返回的是MySQLDialect, 则返回的是
public String getSelectGUIDString() {
   return "select uuid()";
}
但是如果不支持uuid的数据库, 则抛出异常
public String getSelectGUIDString() {
   throw new UnsupportedOperationException( "dialect does not support GUIDs" );
}

3)increment:
public class IncrementGenerator implements IdentifierGenerator, Configurable {
... 
public synchronized Serializable generate(SessionImplementor session, Object object) 
throws HibernateException {

   if (sql!=null) {
    getNext( session ); //注:使用了一个sql: "select max(" + column + ") from " + buf.toString();
   }
   return IdentifierGeneratorFactory.createNumber(next++, returnClass);
}
}
留意这里对generate方法使用了同步, 可想如果所有ID都通过hibernate创建, 则是安全的...

4) foreign key 简而言之, 就是要取到关联的对象的ID
foreign-key的配置稍微繁琐一点, 附上一个例子: 对于帖子(Post)和评论(Comment), Comment表有一个外键fk_post, comment.post_id关联到Post.id. 那么在Comment.hbm.xml中就可以这样配置

Comment.hbm.xml
------------------------------------------------------------
<hibernate-mapping package="work">
    <class name="Comment" lazy="false">
        <id name="id">
            <generator class="foreign">
                <param name="property">post</param>
            </generator>
        </id>
...
        <many-to-one name="post" column="post_id"></many-to-one>
    </class>
</hibernate-mapping>


hibernate源代码:
------------------------------------------------------------
public Serializable generate(SessionImplementor sessionImplementor, Object object) 
throws HibernateException {
    //注:这里object是Comment对象
  
   Session session = (Session) sessionImplementor;

   //注:这里associatedObject是Post对象
   Object associatedObject = sessionImplementor.getFactory()
          .getClassMetadata( entityName )
          .getPropertyValue( object, propertyName, session.getEntityMode() );
  
   if ( associatedObject == null ) {
    throw new IdentifierGenerationException(
      "attempted to assign id from null one-to-one property: " + 
      propertyName
     );
   }
  
   EntityType type = (EntityType) sessionImplementor.getFactory()
        .getClassMetadata( entityName )
        .getPropertyType( propertyName );

   Serializable id;
   try {
    id = ForeignKeys.getEntityIdentifierIfNotUnsaved(
      type.getAssociatedEntityName(), 
     associatedObject, 
      sessionImplementor
     ); 
   }
   catch (TransientObjectException toe) {
    id = session.save( type.getAssociatedEntityName(), associatedObject );
   //注: 尝试保存该对象来生成ID, 这个操作可能触发一系列其他的东西, 如事件, 缓存写入等等
   }

   if ( session.contains(object) ) {
    //abort the save (the object is already saved by a circular cascade)
    return IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR;
    //throw new IdentifierGenerationException("save associated object first, or disable cascade for inverse association");
   }
   return id;
}

5) Identity: 利用数据库的自增长方式来生成ID
相比前面的策略, 这是很有意思的ID生成策略, 因为hibernate并不能在insert前预先获得ID, 而是在insert后, 依赖于JDBC API的PreparedStatement.getGeneratedKeys()方法来取得ID, 该方法返回的是一个ResultSet, 只有一列, 名称为GENERATED_KEY. 所以Hibernate也是采用一种后置处理的方式: 即在调用到IdentifierGenerator.getnerate()方法的时候(其实这个时候的实现是IdentityGenerator类) , 直接返回一个Serilizable对象--IdentifierGeneratorFactory.POST_INSERT_INDICATOR. 接着, 在我们使用session.save(object)方法的时候, 会判断save操作的类型是否为IdentifierGeneratorFactory.POST_INSERT_INDICATOR,再进行相应处理. 

save部分代码量太大, 免了. 看一些关键的.

先是"奇怪"的generate()方法
public abstract class AbstractPostInsertGenerator implements PostInsertIdentifierGenerator {
public Serializable generate(SessionImplementor s, Object obj) {
   return IdentifierGeneratorFactory.POST_INSERT_INDICATOR;
}
}
public class IdentityGenerator extends AbstractPostInsertGenerator {
.. //没有覆盖generate()
}

然后是session.save()对应的事件监听器 AbstractSaveEventListener 的saveWithGeneratedId()
protected Serializable saveWithGeneratedId(...){
...
if ( generatedId == null ) {
    throw new IdentifierGenerationException( "null id generated for:" + entity.getClass() );
   }
   else if ( generatedId == IdentifierGeneratorFactory.SHORT_CIRCUIT_INDICATOR ) {
    return source.getIdentifier( entity );
   }
   else if ( generatedId == IdentifierGeneratorFactory.POST_INSERT_INDICATOR ) {
    return performSave( entity, null, persister, true, anything, source, requiresImmediateIdAccess );
   }
...
}
该方法一直执行到protected Serializable performSaveOrReplicate(...)方法的
if ( useIdentityColumn ) {
    EntityIdentityInsertAction insert = new EntityIdentityInsertAction(
      values, entity, persister, source, shouldDelayIdentityInserts
    );
    if ( !shouldDelayIdentityInserts ) {
     log.debug( "executing identity-insert immediately" );
     source.getActionQueue().execute( insert ); //这里有文章,hibernate已先把先前的操作先转换成sql执行

经过N多处理后, 最后回到刚才提到的JDBC API上. 在IdentityGenerator.GetGeneratedKeysDelegate子类中
   public Serializable executeAndExtract(PreparedStatement insert) throws SQLException {
    insert.executeUpdate();
    ResultSet rs = null;
    try {
     rs = insert.getGeneratedKeys();
     return IdentifierGeneratorFactory.getGeneratedIdentity(rs,persister.getIdentifierType());
    ...  
}
~_~

不得不佩服Hibernate团队的重构能力, 许多功能都被按照"行为向上集中"的规则处理, 即相同的行为, 放在更高层次的父类去. 调式过程中能看到很多类都是继承于AbstractXXX. 并且每个类的责任很明确. 像EntityPersister, Batcher, ActionQueue, Executable和它的实现类, 等等...

Java 中 MySQL 自增 ID 的与案例分析 定义:在 MySQL 中,如果某一列被定义为,则每次插入新记录时,这一列会自动分配一个唯一且递增的值。初始化:自增值从1开始,并随着每次插入操作而递增。持久化:当前的自增值存储在内存中,但在服务器重启或者表重建期间,InnoDB 会从表的数据文件中重新计算最大值并继续递增。 阅读详情

相关推荐

用hibernate形式uuid的生成算法

用hibernate形式的uuid的生成类

org.hibernate.id.IdentifierGenerationException

当出现org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save():异常时,一般是因为元素配置不正确,元素缺少其子元素的配置引起。

qq_32564349的博客 356

LTspice 导入 PSpice 模型实战指南 --(解决语法兼容性与模型优化问题)

本文提供了将PSpice模型成功导入LTspice的详细实战指南。针对两者间的语法兼容性问题,文章以TI UCC23513为例,逐步讲解模型获取、符号创建、常见语法错误修改及仿真验证方法,并分享了模型优化与个人库管理技巧,帮助用户高效解决模型导入与仿真难题。

weixin_28278377的博客 861

hibernate id策略

Hibernate的id生成有N种策略, 可以通过hbm文件或者annotationhibernate 源码配置. 支持的策略包括:uuid, hilo, assigned, identity,hibernate 源码分析 select, sequence, seqhilo, increment, foreign, guid, uuid.hex, sequence-identity. ...

J2EE 226

别再傻傻分不清!5分钟搞懂倾斜摄影里‘地面分辨率’和‘模型精度’到底啥关系

本文深入解析倾斜摄影中‘地面分辨率’与‘模型精度’的关系,帮助读者快速理解两者的本质区别与内在关联。通过实战案例和公式计算,详细说明如何从航飞设计到精度验证全流程控制,避免常见认知误区,并针对不同应用场景提供精度需求建议。

weixin_33700350的博客 484

ENVI 5.6保姆级教程:高分七号DLC影像从打开到融合的完整流程(附避坑指南)

本文详细介绍了ENVI 5.6处理高分七号DLC影像的完整流程,包括环境准备、数据解压、正射校正、图像融合等关键步骤。特别针对国产卫星数据处理的独特挑战,提供了实用的避坑指南和优化技巧,帮助用户高效完成光学影像的预处理和质量提升。

weixin_33269743的博客 388

【吐血整理】Hibernate常用的主键生成策略的原理、优缺点、应用场合

通过简介以及详细讲解主键生成策略的不同属性的功能

机智猫 1万+

保姆级教程:用掘金量化API手把手复现一个年化17%的网格交易策略(附完整Python代码)

本文提供了一份详细的掘金量化API教程,手把手教你构建一个年化17%的网格交易策略。通过完整的Python代码实现,深入解析网格交易的核心逻辑、参数配置和动态调仓机制,帮助量化新手快速掌握策略开发全流程。教程包含环境配置、代码实现、回测分析和常见问题解答,是学习量化投资的实用指南。

weixin_33709364的博客 304

Hibernate 主键&存储过程

一、 JPA通用策略生成器 通过annotation来映射hibernate实体的,基于annotation的hibernate主键标识为@Id, 其生成规则由@GeneratedValue设定的.这里的@id和@GeneratedValue都是JPA的标准用法, JPA提供四种标准用法,由@GeneratedValue的源代码可以明显看出.       public enumGe

talent210的专栏 1458

Python爬虫实战:使用Scrapy+Playwright高效爬取全球专利数据库

本文将详细介绍如何使用Python最新技术栈(Scrapy+Playwright)构建一个高效的专利数据库爬虫系统。我们将从爬虫基础知识讲起,逐步深入到反爬应对策略、分布式爬虫架构以及数据存储方案,最终实现一个完整的专利数据采集系统。专利数据是技术创新领域的重要信息资源,包含技术描述、权利要求、申请人信息等宝贵数据。中国国家知识产权局(CNIPA)美国专利商标局(USPTO)欧洲专利局(EPO)世界知识产权组织(WIPO)

2201_76125261的博客 1396

【Qwen2微调实战】LLaMA-Factory框架对Qwen2-7B模型的微调实践

在人工智能的浪潮中,大型语言模型(LLMs)正逐渐成为研究和应用的热点。它们在自然语言处理(NLP)的各个领域,如文本生成、翻译、问答等任务中展现出了卓越的能力。Qwen2-7B模型,作为该领域的佼佼者,不仅因其庞大的参数量和强大的表示能力受到关注,更因其在微调后能够更好地适应特定任务而备受关注。本文将详细介绍如何利用LLaMA-Factory这一高效的微调框架对Qwen2-7B进行微调,以期达到提升模型在特定任务上的表现。

寻道AI,探索AI无限可能! 2万+

【hibernate框架】uuid与native生成ID的样例-XML配置

native算法生成随机id: native 根据底层数据库的能力选择 identity、sequence 或者 hilo 中的一个。 native算法指定的字段类型: 用mysql,你需要设置主键bigint, autoincreament (大数,自增) 用oracle,你需要设置主键bigint, sequence  这样才能在hibernate中指定native

程序猿之洞 5585

机器学习扩散模型简介

​ 扩散模型是生成模型,在过去几年中越来越受欢迎,这是有充分理由的。仅在 2020 年代发布的几篇开创性论文就向世界展示了 Diffusion 模型的能力,例如在图像合成方面击败 GAN[6]。最近,从业者将看到DALL-E 2(OpenAI 上个月发布的图像生成模型)中使用的扩散模型。

gongdiwudu的专栏 4295

jpa 获取多个生成的id_java – 如何在使用JPA和Hibernate时选择id生成...

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hi...

weixin_39928003的博客 87

基于STM32设计的环境检测系统(OneNet)_365

本项目设计并实现了一种基于STM32F103RCT6单片机的环境检测系统,系统集成了多种传感器模块,具备对环境温湿度、烟雾浓度、易燃气体浓度、一氧化碳浓度和整体空气质量的实时检测功能。系统通过1.44寸SPI接口LCD实现本地数据显示,同时配备有源蜂鸣器用于环境异常报警。在数据通信方面,系统利用ESP8266-WIFI模块,采用MQTT协议将各类传感器数据上传至OneNet云平台,并借助其可视化框架实现网页端可视化界面,可通过电脑和手机浏览器远程访问,实现环境数据的远程监控。该系统设计结构简单、功能全面,适

2291

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

看Hibernate源码 003 - ID Generator

Hibernate的id生成有N种策略, 可以通过hbm文件或者annotation配置. 支持的策略包括:uuid, hilo, assigned, identity, select, sequence, seqhilo, increment, foreign, guid, uuid.hex, sequence-identity. 对应这些策略, 可以在org.hibernate.id包下找...

wjboy49的专栏 229

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

020_ID生成策略_XML_配置

博客分类: 星期六, 一月 02, 2016  14:04:55     id生成策略 1.对应项目:hibernate_0400_ID 2.注意:     a)我们观察hibernate生成表的结构并不是为了将来就用它生成,(可能还有自己的扩展,比如index等) 而是为了明白我们应该建立什么样的表和实体类映射。

dotedy的博客 427

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

hibernate id 设置(解决多进程 id 冲突)

 type (可选): 标识Hibernate类型的名字。 column (可选 - 默认为属性名): 主键字段的名字。 unsaved-value (可选 - 默认为null): 一个特定的标识属性值,用来标志该实例是刚刚创建的,尚未保存。这可以把这种实例和从以前的session中装载过(可能又做过修改--译者注)但未再次持久化的实例区分开来。 access (可选 - 默认为property)

xuexijava的专栏 1102

看Hibernate源码之 ID Generator

Hibernate的id生成有N种策略, 可以通过hbm文件或者annotation配置. 支持的策略包括:uuid, hilo, assigned, identity, select, sequence, seqhilo, increment, foreign, guid, uuid.hex, sequence-identity. 对应这些策略, 可以在org.hibernate.id包

专注于编程技术 908

分布式Unique ID的生成原理

分布式Unique ID的生成原理

杨鑫newlife的专栏 993

hibernate id 映射配置

hibernate id 映射配置

binziwell的专栏 508

Spring Data JPA使用sequence生成主键

一、实体类配置 @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "operator_seq") private Long id; 二、说明 表示使用名为"operator_seq"的序列,默认分配的值为50(可以在@SequenceGenerator(name = “operator_seq”, allocationSize = 50)中进行更改)。 实际使用中发现,批量保存多条记录时(repository.saveA

李剑 1889

hibernate 主键生成方式

<br />Key Generator<br /> 主键产生器<br /> 可选项说明:<br /> 1) assigned<br /> 主键由外部程序负责生成,无需Hibernate参与。<br /><br /> 2) hilo<br /> 通过hi/lo 算法实现的主键生成机制,需要额外的数据库表保存主<br /> 键生成历史状态。<br /><br /> 3) seqhilo<br /> 与hilo 类似,通过hi/lo 算法实现的主键生成机制,只是主键历史<br /> 状态保存在

hld_hepeng的专栏 523

Hibernate知识点总结

1.HelloWorld a.xml b.annotation2.Hibernate原理模拟,什么是O/R Mapping以及为什么要有这个?3.常见的O/RKUANGJIAN 4.基础配置5.核心接口介绍6.对象的三种状态7.ID生成策略8.关系映射9.hibernate查询(HQL)10.在struts基础上继续完善项目11.性能优化12.补充话题----------------...

aq9618154的博客 170

Hibernate 专题研究系列(一) save/update/saveOrUpdate等方法学习

  知识准备 1 所有Entity实体在其hbm.xml配置文件中都必须设置Id元素或composite-id元素,不然hbm.xml文件会报错。 因此,任何情况下Entity都拥有IdentifierGenerator对象,即关键列生成策略。 &lt;id name="id" type="string"&gt;     &lt;column name...

poethelasi1的博客 263
上一篇: 文件下载问题
下一篇: Java系统程序员修炼之道
gufengjava
博客等级 码龄16年 1粉丝 59原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址