ITeye博客

为MongoDB增加自增长主键生成的功能

yongtree · 2011-01-21 09:05 · NoSQL · 企业架构 · Markdown

每个MongoDB的document都有一个_id字段作为它的第一个属性,这个值通常是一个BSON对象id,因此,这个id对于集合中的每个成员都是唯一的,如果用户插入一个document没有提供一个id,数据库将自动生成一个id,并存储在_id字段。   
   The BSON ObjectId Datatype   
一个BSON ObjectID是由12个字节组成:4字节时间+3字节机器id+2字节进程id+3字节的数字
{ "_id" : ObjectId("4c691e72ed2a47b462dfa806") }

有时候我们的应用中需要自增长的数字型主键,MongoDB在这方面并没有给我们提供支持,我们需要加以改造,使其具有自增长主键生成的功能。此次的功能改造,依赖的是morphia开源项目(MongoDB在java语言上的ORM实现,http://code.google.com/p/morphia/),直接上代码吧。

首先定义一个保存各个 collection的主键增量值的系统配置collection:StoredSeqence

java 代码

  1. /**
  2. * MongoDB自增长主键维护队列,类似于MSSQL,Oracle维护主键的方式
  3. *
  4. * @author yongtree
  5. * @date 2011-1-17 下午06:58:05
  6. * @version 1.0
  7. */
  8. @Entity(noClassnameStored=true)
  9. public class StoredSeqence implements Serializable {
  10. private static final long serialVersionUID = 1L;
  11. @Id
  12. String collName;
  13. Long value;
  14. public StoredSeqence(){
  15. }
  16. public StoredSeqence(String collName) {
  17. this.collName = collName;
  18. }
  19. public Long getValue() {
  20. return value;
  21. }
  22. public void setValue(Long value) {
  23. this.value = value;
  24. }
  25. public String getCollName() {
  26. return collName;
  27. }
  28. public void setCollName(String collName) {
  29. this.collName = collName;
  30. }
  31. }

然后定义一个实体的基类,在基类中处理主键生成。

java 代码

  1. /**
  2. * 自增长数字类型主键的Mongo实体
  3. *
  4. * @author yongtree
  5. * @date 2011-1-17 下午04:11:04
  6. * @version 1.0
  7. */
  8. public abstract class LongPKMongoEO extends BaseMongoEO {
  9. @Id
  10. Long _id;
  11. @Transient
  12. protected Datastore ds;
  13. public void setDs(Datastore ds) {
  14. this.ds = ds;
  15. }
  16. @PrePersist
  17. void prePersist() {
  18. //自增性主键的处理
  19. if (_id == null) {
  20. String collName = ds.getCollection(getClass()).getName();
  21. Query<StoredSeqence> q = ds.find(StoredSeqence.class, "_id",
  22. collName);
  23. StoredSeqence ss = q.get();
  24. if(ss==null){//不存在该实体的注册,则新创建一个
  25. ss = new StoredSeqence(collName);
  26. ss.setValue(1l);
  27. }else{
  28. ss.setValue(ss.getValue()+1);
  29. }
  30. ds.save(ss);
  31. _id=ss.value;
  32. }
  33. }
  34. public Long getId() {
  35. return _id;
  36. }
  37. }

这样自增长主键的生成的主要功能基本上已经完成了,具体如何使用,接下来将根据实际的项目再做介绍,请继续关注我的博客。

 

原文:http://www.po-soft.com/hi/yongtree/blog/2157

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。