`
fantaxy025025
  • 浏览: 1279578 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类

DB_ID_UUID一个实现

阅读更多

ID Generator

A lot of us (until recently myself included) tend to use Sequence generators to generate PKs. These are well known to anybody who used Oracle or any other RDBMS. Sequences, however tend to have a number of issues:

  • They require an extra database object for each ID. Those need to be part of DDL, and are yet another moving part when deploying code changes. How many of us deployed new code, only to find out we forgot to create corresponding sequences.
  • If you ever plan on exposing your objects outside (like datawarehouse for example) the sequences need to be staggered across all your partitions and regions. This is a manual, error prone process.

Instead consider using a UUID generator with a time prefix to create a 29 char unique id. You will need to create a custom UUID generator:

import java.nio.ByteBuffer;
import java.util.UUID;

import org.apache.commons.codec.binary.Base64;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;

/**
 * Generates a UUID used for a hibernate ID.
 */
public class UUIDGenerator implements IdentifierGenerator {
	/**
	 * Returns a Base64-encoded UUID with a time prefix. The Base64 encoding is
	 * there to shorten the length of the ID (without losing any information in
	 * the process).
	 */
	@Override
	public String generate(SessionImplementor session, Object object) {
		// Create a new byte buffer packed with the 128-bits from a randomly
		// generated UUID
		UUID uuid = java.util.UUID.randomUUID();

		ByteBuffer bb = ByteBuffer.allocate(16)
			.putLong(uuid.getMostSignificantBits()) // First 8 bytes
			.putLong(uuid.getLeastSignificantBits()); // Last 8 bytes

		// Base-64 encode the UUID, remove the trailing '='
		String base64 = new String(Base64.encodeBase64(bb.array())).substring(0, 22);

		// Prepend date + hour to the application to optimize block caching on
		// Oracle side
		// See Grant McAlister's POA presentation for the reasons behind that
		String prefix = new DateTime(DateTimeZone.UTC).toString(DateTimeFormat.forPattern("yyyyDDD"));

		// Done
		return prefix + base64;
	}
}
 

 

 

Next, all you need is to declare this UUID generator on your PKs:

 

	 @Entity
	 @Table(name = "MY_ENTITY")
	 @org.hibernate.annotations.GenericGenerator(name = "uuid-generator", strategy = "UUIDGenerator")
	 public class Entity {
	     @Id
	     @Column(name = "ID", length = 29)
	     @GeneratedValue(generator = "uuid-generator")
	     private String id;
	 }
 

 

(Thumbsup.gifRECOMMENDED ) See Grant McAlister's January 2010 PoA GEMs talk on UUIDs to learn about how to prefix GUIDs/UUIDs with time information to drastically minimize impact on your databases during writes for high insert rate applications.

 

Other topics:

A Quick Guide : http://betterexplained.com/articles/the-quick-guide-to-guids/

 

 

分享到:
评论

相关推荐

    CREATE_DB_AND_TABLE_add_edit_del-pw.rar_CREATE_DB_AND_TABLE_Tabl

    例如,创建一个名为"Employees"的新表: ```cpp cmd->CommandText = "CREATE TABLE Employees (ID AUTOINCREMENT PRIMARY KEY, Name VARCHAR(50), Position VARCHAR(50))"; cmd->Execute(NULL, NULL, adCmdText); ``...

    MySQL主从同步中的server-id示例详解

    **server-id** 是 MySQL 实例的一个唯一标识符,用于区分主从节点。当搭建主从复制环境时,每个实例的 `server-id` 必须是唯一的,且数值不能为0,因为0会阻止从库的连接。默认情况下,MySQL 的 `server-id` 值为0,...

    OpenStack源码分析-NOVA

    # 返回匹配的db.models.S3Image.uuid给image_uuid; image_uuid = ec2utils.id_to_glance_id(context, image['id']) # 获取镜像image的状态; if image: image_status = image['status'] ``` ##### 2. 方法...

    wabacus制作的一个填写周报的小例子_oracle版

    这是一个用wabacus3.4制作的小例子(本地环境wabacus3.4+tomcat7+jdk1.7+oracle10g), 是用来让部门成员填写周报的, 内容包括了登录,填写周报,查看报告,权限管理,保存用户个性化信息(主题,列排序,列拖动,列选择)等等 ...

    使用Ruby on Rails和PostgreSQL自动生成UUID的教程

    这是一个PostgreSQL的开源扩展,提供了生成UUID的函数,如`uuid_generate_v1()`, `uuid_generate_v3()`, `uuid_generate_v4()`和`uuid_generate_v5()`。其中,`uuid_generate_v4()`是最常用的,它基于随机数生成UUID...

    一个简单的Redis开发教程

    # 创建一个 session session_data = "User ID: 12345" session_id = create_session(session_data) print(f"Created session with ID: {session_id}") # 获取 session 数据 retrieved_data = get_session...

    javabean(DB)

    总的来说,`javabean(DB)`指的是一个与数据库操作相关的JavaBean组件,它可能包含一系列用于数据库交互的方法和属性,是Java应用中数据持久化和业务处理的关键部分。在实际项目中,我们需要根据具体需求来设计和使用...

    clinical_tcga:用于解析来自 TCGA 的临床元数据文件的库

    临床_tcga 用于从 TCGA 解析元... 如果还包括一个 UUID 到条形码 ID 的转换工具。 单个 UUID 可以这样转换: convert_tcga_uuid.rb sample_uuid或者多个 UUID 在作为文件提供时可以一次转换: convert_tcga_uuid.rb -f

    VCDB.rar_vc和vcdb

    在本案例中,"VCDB.rar_vc和vcdb"是一个与VC++相关的压缩包,包含了用于通过OLEDB访问数据库的封装类。OLEDB是微软提出的一种数据访问接口,它允许开发者直接访问多种类型的数据源,如SQL Server、Access、Excel等,...

    Mysql全局ID生成方法

    MySQL全局ID生成方法是数据库设计中的一个重要议题,特别是在大规模分布式系统中,确保ID的全局唯一性和高并发下的高效生成是数据库架构的关键要素。以下是一些常见的全局ID生成策略: 1. **基于CAS(Check and Set...

    is_rateable:降低 Rails 应用的评分

    rateable:install$ rake db:migrate如果您使用 UUIDS: $ rails generate is_rateable:install --id_column_type uuid$ rake db:migrate这可以确保您的参考rater和ratee采用的是:uuid列,而不是一个:integer一个配置...

    基于django 的orm中非主键自增的实现方式

    值得注意的是,Django 默认情况下,如果模型没有显式声明主键,它会自动添加一个名为 `id` 的 `AutoField` 作为主键,这会在数据库中创建一个自动递增的整数字段。例如: ```python class Student(models.Model): ...

    VC++中Ado操作acess数据库

    首先,需要创建一个`Connection`对象,然后使用`Open`方法打开数据库。代码示例如下: ```cpp BOOL CMy123App::InitInstance() { AfxEnableControlContainer(); CoInitialize(NULL); // ... _ConnectionPtr m_...

    abing:使用FASTAPI进行FAST AB测试集成

    在用户界面中创建并设置实验后,您可以通过从路由API(/ api / v1 / experiments / route)接收每个用户ID(如有必要,为uuid)的分配来自由地执行AB测试。 入门 安装 您可以使用pip快速安装它,如下所示。 pip ...

    VC++使用ADO开发ACCESS数据库.pdf

    这将创建一个名为TestTable的新表,包含一个自动递增的主键字段ID和一个VARCHAR类型的Name字段。 至于_RecordsetPtr,你可以使用它来填充数据或执行查询: ```cpp _RecordsetPtr m_pRecordset = NULL; m_...

    数据库集群部署—TY.docx

    在服务器上解压GI和oracle软件的zip 包 [root@dbrac1 opt]# unzip ...看此命令是否能获取到磁盘的UUID值,正常情况是能获取到的,如果没有获取到,请查检12cdbrac1.vmx文件中是否添加了这一项disk.EnableUUID = "TRUE

    C++(MFC)连接SQL2008语句

    MFC(Microsoft Foundation Classes)是微软为简化Windows应用程序开发而提供的一个类库,它封装了Windows API的复杂性,使开发者能够更高效地创建具有丰富图形用户界面的应用程序。 ### SQL Server 2008 SQL ...

    利用Python的Flask框架来构建一个简单的数字商品支付解决方案

    总结,通过Flask和Python,我们可以快速构建一个数字商品支付系统,实现用户友好的购买流程、安全的支付处理、自动化的邮件发送以及数据库驱动的下载管理。尽管这里展示的代码简化了许多细节,但它展示了如何利用...

    lab_azure_build-cassandra-app-with-python-sdk-azure-cosmos-db

    在这个实验“lab_azure_build-cassandra-app-with-python-sdk-azure-cosmos-db”中,我们将探讨如何使用Python SDK与Azure Cosmos DB的Cassandra API来构建一个应用程序。Azure Cosmos DB是微软提供的一款全球分布式...

Global site tag (gtag.js) - Google Analytics