网站首页
JSP空间
动态资讯
开源项目
技术文档
资源下载
J2EE资源
客户论坛
在线支付
 
  技术文档>>JAVA>>新手入门>>基础入门>查看文档  
  教你用java id生成器去生成逻辑主键     
  文章作者:未知  文章来源:水木森林  
  查看:73次  录入:管理员--2007-11-17  
 
  在一个数据库设计里,假如使用了逻辑主键,那么你一般都需要一个id生成器去生成逻辑主键。
  
  在许多数据库里面,都提供了id生成的机制,如oracle中的sequence,mssql中的identity,可惜这些方法各种数据库都不同的,所以很多人愿意找寻一种通用的方式。
  
  编写代码,1、2、3……这样一直累加是最直接的想法,java用以下方式去实现
  
  private static atomicinteger uniqueid = new atomicinteger(0);
  
  public static string nextid() {
  return integer.tostring(uniqueid.incrementandget());
  }
  
  当然,这样太简单了,并且一重新启动,计数器就归 0 了,一般的做法可以用 时间 + 计数器 的方式,
  
  private static final long one_step = 10;
  private static final long base = 1129703383453l;
  
  private static final lock lock = new reentrantlock();
  
  private static long lasttime = system.currenttimemillis();
  private static short lastcount = 0;
  
  /**
  * a time (as returned by {@link system#currenttimemillis()}) at which
  * the vm that this uid was generated in was alive
  * @serial
  */
  private final long time;
  
  /**
  * 16-bit number to distinguish uid instances created
  * in the same vm with the same time value
  * @serial
  */
  private final short count;
  
  /**
  * generates a uid that is unique over time with
  * respect to the host that it was generated on.
  */
  public uid() {
  lock.lock();
  try {
  if (lastcount == one_step) {
  boolean done = false;
  while (!done) {
  long now = system.currenttimemillis();
  if (now == lasttime) {
  // pause for a second to wait for time to change
  try {
  thread.currentthread().sleep(1);
  }
  catch (java.lang.interruptedexception e) {
  } // ignore exception
  continue;
  }
  else {
  lasttime = now;
  lastcount = 0;
  done = true;
  }
  }
  }
  time = lasttime;
  count = lastcount++;
  }
  finally {
  lock.unlock();
  }
  }
  在一个群集的环境里面,通常还需要加上ip的前缀,即 ip + 时间 + 计数器,这个就是java原版本的实现了。
  
  但是,觉得这个id太长了?那没办法,回到用数据库的方法吧。
 
 
上一篇: 来龙去脉 jdo技术分析及企业应用研究    下一篇: sqlserver 2000h 和 jdbc 的融合问题
  相关文档
java反编译的研究 11-16
java调试教程--服务器端调试 11-17
parsefloat 方法 11-16
struts框架 11-17
java二进制兼容性概述 11-17
java数据对象(jdo)快速入门 11-17
在eclipse中使用junit 11-17
作了个小测试equals 和== 11-17
应用:tomcat5配置mysql jdbc数据库连接池 04-08
人们眼中的安全 11-17
java模式设计之多态模式与多语言支持 11-17
关于线程的讲解(出自java原著) 11-17
使用iterator节省代码 11-17
j2ee编程起步(1) 11-17
java规则中级篇 11-17
头条:webwork将加入struts! 11-17
浅谈java与c#的事件处理机制 11-17
java、j2ee基础问题汇总 11-17
用j2se1.5来实现多任务的java应用程序 11-16
java虚拟机的研究与实现 11-17
返回首页 | 关于我们 | J网章程 | JSP空间合租 | 客服中心 | 免责声明 | 常见问题 | 参观机房
本站主机空间代理至厦门市华众网络科技有限公司
《中华人民共和国增值电信业务经营许可证》
编号:闽B2-20050079
@2005-2008福建JSP技术网 版权所有 闽ICP备05000928号
厦门(总部):13616026886 福州:0591-87655121
邮箱:admin@fjjsp.com 站长QQ,点击这里给我发消息