java之BerkeleyDB(二)--绑定(Binding)技术、游标(Cursor)

来源:互联网 发布:淘宝买二手显卡靠谱吗 编辑:程序博客网 时间:2024/06/06 07:43

转自: http://blog.csdn.net/ylf13/article/details/15337957

有几个注意的,在BDB数据库里,默认是不能有重复的两个相同的键,当然可以通过config配置sortedDupli...来设置可以,所以在读取数据库值的时候必须考虑两种情况,是否存在相同的键的记录

JE provides two basic mechanisms for the storage and retrieval of database key/data pairs:

  • The Database.put() and Database.get() methods provide the easiest access for all non-duplicate records in the database. These methods are described in this section.

  • Cursors provide several methods for putting and getting database records. Cursors and their database access methods are described in Using Cursors.

看完上段OK,如果是设置non-duplicate,那就直接用db.get() db.put()来操作记录。否则就得用Cursor了

  • Database.put()

  • Database.putNoOverwrite()

  • Database.putNoDupData()

  • Database.get()  这个利用key来找

  • Database.getSearchBoth() 这个利用Key和value共同找记录

delete函数:如果记录是支持duplicate,则删除所有满足的key的记录,如果想删除某一条,还是得用cursor


上篇我们简单的打开了数据库和进行简单的存储

这个对于我们存储数据的基本类型还行,但是涉及到用户自定义类的时候,单靠之前的转换函数来从string转换程对象是不妨便的,我们来看看BDB为我们准备来什么?

引自使用手册:

DatabaseEntry can hold any kind of data from simple Java primitive types to complex Java objects so long as that data can be represented as a Java byte array. Note that due to performance considerations,you should not use Java serialization to convert a Java object to a byte array. Instead, use the Bind APIs to perform this conversion (see Using the BIND APIs for more information).


看到加粗这段了把,官方推荐我们用Bind

(一)Bind技术

(1)SeriaBinding

先说下序列化的绑定技术,言外之意,我们的数据类型就必须实现Serializable才能进行下面的绑定

Serializing Objects

To store a serializable complex object using the Bind APIs:

  1. Implement java.io.Serializable in the class whose instances that you want to store.

  2. Open (create) your databases. You need two. The first is the database that you use to store your data. The second is used to store the class information.

  3. Instantiate a class catalog. You do this withcom.sleepycat.bind.serial.StoredClassCatalog, and at that time you must provide a handle to an open database that is used to store the class information.

  4. Create an entry binding that uses com.sleepycat.bind.serial.SerialBinding.

  5. Instantiate an instance of the object that you want to store, and place it in a DatabaseEntryusing the entry binding that you created in the previous step.

其实绑定技术就是用了反射。

没看源码,也没什么好展开的,大家就把方法记着吧,以后再一步步来

由于需要用到Class这个类,所以构造函数多了一个value的Class

这样就可以使得我们自己数据完整的存入了


[cpp] view plaincopy
  1. import java.io.File;  
  2. import java.io.Serializable;  
  3. import java.io.UnsupportedEncodingException;  
  4.   
  5. import com.sleepycat.bind.EntryBinding;  
  6. import com.sleepycat.bind.serial.SerialBinding;  
  7. import com.sleepycat.bind.serial.StoredClassCatalog;  
  8. import com.sleepycat.bind.serial.TupleSerialBinding;  
  9. import com.sleepycat.bind.tuple.TupleBase;  
  10. import com.sleepycat.bind.tuple.TupleBinding;  
  11. import com.sleepycat.bind.tuple.TupleTupleBinding;  
  12. import com.sleepycat.je.Database;  
  13. import com.sleepycat.je.DatabaseConfig;  
  14. import com.sleepycat.je.DatabaseEntry;  
  15. import com.sleepycat.je.Environment;  
  16. import com.sleepycat.je.EnvironmentConfig;  
  17. import com.sleepycat.je.LockMode;  
  18. import com.sleepycat.je.OperationStatus;  
  19.   
  20.   
  21. public class Main {  
  22.   
  23.     /** 
  24.      * @param args 
  25.      */  
  26.     static Environment env = null;  
  27.       
  28.     public static void main(String[] args) {  
  29.         BDBUtil<Integer, Student> bDB = new BDBUtil<Integer, Student>("testDB",Student.class);  
  30.         Student s1 = new Student(1,"ylf");  
  31.         Student s2 = new Student(2,"dsb");  
  32.         Student s3 = new Student(3,"dbc");  
  33.           
  34.         bDB.put(1, s1);  
  35.         bDB.put(2, s2);  
  36.         bDB.put(3, s3);  
  37.           
  38.         Student s = bDB.get(3);  
  39.         System.out.println("my name is "+s.getName()+" no is "+s.getNo());  
  40.           
  41.         System.out.println(bDB.size());  
  42.         bDB.close();  
  43.     }  
  44.   
  45. }  
  46.   
  47. /** 
  48.  * 我们的BDB工具 
  49.  * 目前对外提供添加数据和取得数据,删除数据3个接口 
  50.  * 类似HashMap的使用方法 
  51.  * 注意: 
  52.  * 这里的K 和 V两个类都必须实现来Serializable 
  53.  * 而且也实现来toString 
  54.  * 使用结束记得调用close() 
  55.  * @author ylf 
  56.  *  
  57.  * 版本2: 
  58.  * 采用动态的数据类型绑定,不是利用我们的toString()来转换对象和Entry 
  59.  * 用到EntryBinding 和StoredClassCatalog 
  60.  * 以及binding.OnjectToEntry()  EntryToObject() 
  61.  * 
  62.  */  
  63. class BDBUtil<K, V>{  
  64.     private Environment env = null;  
  65.     private EnvironmentConfig envCfig = null;  
  66.     private Database db = null;  
  67.     private DatabaseConfig dbCfig = null;  
  68.       
  69.     private Database classDB = null;  
  70.     private StoredClassCatalog classCatalog = null;  
  71.     private EntryBinding valueBinding = null;  
  72.       
  73.     private File file = null;  
  74.       
  75.     public BDBUtil(String dbName, Class valueClass) {  
  76.         envCfig = new EnvironmentConfig();  
  77.         envCfig.setAllowCreate(true);  
  78.         file = new File("./test/");  
  79.         env = new Environment(file, envCfig);  
  80.         dbCfig = new DatabaseConfig();  
  81.         dbCfig.setAllowCreate(true);  
  82.         db = env.openDatabase(null, dbName, dbCfig);  
  83.           
  84.         //首先创建一个我们类的数据库  
  85.         classDB = env.openDatabase(null, "classDB", dbCfig);  
  86.         //实例化一个Catalog  
  87.         classCatalog = new StoredClassCatalog(classDB);  
  88.         //实例化一个binding来转换  
  89.         valueBinding = new SerialBinding(classCatalog, valueClass);  
  90.     }  
  91.       
  92.     public boolean put(K key, V value){  
  93.         DatabaseEntry keyEntry = new DatabaseEntry(key.toString().getBytes());  
  94.         DatabaseEntry valueEntry = new DatabaseEntry();  
  95.         valueBinding.objectToEntry(value, valueEntry);  
  96.           
  97.         db.put(null, keyEntry, valueEntry);  
  98.         return true;  
  99.     }  
  100.       
  101.     public V get(K key){  
  102.         DatabaseEntry keyEntry;  
  103.         V value = null;  
  104.         try {  
  105.             keyEntry = new DatabaseEntry(key.toString().getBytes("gb2312"));  
  106.             DatabaseEntry valueEntry = new DatabaseEntry();  
  107.             if(db.get(null,keyEntry,valueEntry,LockMode.DEFAULT) == OperationStatus.SUCCESS){  
  108.                 value = (V)valueBinding.entryToObject(valueEntry);  
  109.                 return value;  
  110.             }  
  111.         } catch (UnsupportedEncodingException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.         return value;  
  115.           
  116.     }  
  117.       
  118.     public boolean del(K keyStr){  
  119.         DatabaseEntry key;  
  120.         try {  
  121.             key = new DatabaseEntry(keyStr.toString().getBytes("gb2312"));  
  122.             if(OperationStatus.SUCCESS == db.delete(null, key))  
  123.                 return true;  
  124.         } catch (UnsupportedEncodingException e) {  
  125.             e.printStackTrace();  
  126.         }  
  127.         return false;  
  128.     }  
  129.       
  130.     public long size(){  
  131.         return db.count();  
  132.     }  
  133.       
  134.     public void close(){  
  135.         db.close();  
  136.         classDB.close();  
  137.         env.cleanLog();  
  138.         env.close();  
  139.     }  
  140. }  
  141.   
  142. /** 
  143.  * 序列化了的类 
  144.  * 实现toString() 
  145.  * @author ylf 
  146.  * 
  147.  */  
  148. class Student implements Serializable{  
  149.     /** 
  150.      *  
  151.      */  
  152.     private static final long serialVersionUID = 7333239714054069867L;  
  153.     private String name;  
  154.     private int no;  
  155.       
  156.     public Student() {  
  157.     }  
  158.     public Student(int no, String name){  
  159.         this.no = no;  
  160.         this.name = name;  
  161.     }  
  162.     public String getName() {  
  163.         return name;  
  164.     }  
  165.     public void setName(String name) {  
  166.         this.name = name;  
  167.     }  
  168.     public int getNo() {  
  169.         return no;  
  170.     }  
  171.     public void setNo(int no) {  
  172.         this.no = no;  
  173.     }  
  174.     @Override  
  175.     public String toString() {  
  176.         return "Student"+no+":"+name;  
  177.     }  
  178.       
  179.     public void fromString(String str){  
  180.         int i = str.indexOf(':');  
  181.         String noStr = str.substring(7,i);  
  182.         this.no = Integer.parseInt(noStr);  
  183.         this.name = str.substring(i+1);  
  184.     }  
  185.       
  186. }  


[cpp] view plaincopy
  1. my name is dbc no is 3  
  2. 3  


(2)自定义绑定

官方还推荐使用custom tuple binding

就是我们实现TupleBinding,实现里面的objectToEntry()  EntryToObject()

这里就不需要维护第二个数据库了,有木有又回到远点的赶脚!!

还不如上一篇里直接在类里实现转换

只不过官方推荐的这种是用字节流来存储,省流量,我们类里也可以利用ArrayByteInputStream好像是这个。。。我忘了,就字节流来实现就好了


(二)游标cursor

游标操作类似数据库的游标。

这里通过getNext() getPrev()来实现遍历

同时,cursor还提供了查找和插入数据的功能,我这里就不再一一写出来了,具体用到的时候在设计吧,现在全部封装一遍也不见得很好。。


[cpp] view plaincopy
  1. interface BDBIterator{  
  2.     public Object currentValue();  
  3.     public Object currentKey();  
  4.     public boolean hasNext();  
  5.     public boolean hasPrev();  
  6.     public void close();  
  7. }  


这里迭代器实现的是BDBUtil的内部类,迭代器的实现大家可以参考Java的迭代器实现方法。

[cpp] view plaincopy
  1. public BDBIterator getIterator(){  
  2.         IteratorImpl it = new IteratorImpl();  
  3.         return it;  
  4.     }  
  5.       
  6.     /** 
  7.      * 这个内部类模拟iterator遍历器 
  8.      * @author ylf 
  9.      * 迭代器使用方法 
  10.      * 首先利用BDBUtil获得迭代器 
  11.      * hasNext()如果下一个元素存在,游标下移动,值通过currentKey currentValue获取 
  12.      * hasPrev()向前移动 
  13.      * 最后记得close() 虽然我这里已经通过null来保证自动close()但不是线程安全的 
  14.      *  
  15.      */  
  16.     class IteratorImpl implements BDBIterator{  
  17.         K currentKey = null;  
  18.         V currentValue = null;  
  19.         DatabaseEntry keyEntry = null;  
  20.         DatabaseEntry valueEntry = null;  
  21.           
  22.         public IteratorImpl() {  
  23.             if(cursor != null){  
  24.                 cursor.close();  
  25.                 cursor = null;  
  26.             }  
  27.             cursor = db.openCursor(null, null);//这里不配值CursorConfig了  
  28.         }  
  29.           
  30.         @Override  
  31.         public void close(){  
  32.             cursor.close();  
  33.             cursor = null;  
  34.         }  
  35.         @Override  
  36.         public Object currentKey() {  
  37.             return currentKey;  
  38.         }  
  39.         @Override  
  40.         public Object currentValue() {  
  41.             return currentValue;  
  42.         }  
  43.   
  44.         @Override  
  45.         public boolean hasNext() {  
  46.             keyEntry = new DatabaseEntry();  
  47.             valueEntry = new DatabaseEntry();  
  48.             cursor.getNext(keyEntry, valueEntry, LockMode.DEFAULT);  
  49.             return has();  
  50.         }  
  51.         @Override  
  52.         public boolean hasPrev() {  
  53.             keyEntry = new DatabaseEntry();  
  54.             valueEntry = new DatabaseEntry();  
  55.             cursor.getPrev(keyEntry, valueEntry, LockMode.DEFAULT);  
  56.             return has();  
  57.         }  
  58.           
  59.         public boolean has(){  
  60.             if(keyEntry.getData() == null)  
  61.                 return false;  
  62.             try {  
  63.                 currentKey = (K) new String(keyEntry.getData(),"gb2312");  
  64.                 currentValue = (V) valueBinding.entryToObject(valueEntry);  
  65.                 if(currentValue != null)  
  66.                     return true;  
  67.             } catch (UnsupportedEncodingException e) {  
  68.                 e.printStackTrace();  
  69.             }  
  70.             return false;  
  71.         }  
  72.           
  73.     }  


调用方式如下:主要还是这个Iterator迭代器的实现遍历看下吧

[cpp] view plaincopy
  1. public static void main(String[] args) {  
  2.         BDBUtil<Integer, Student> bDB = new BDBUtil<Integer, Student>("testDB",Student.class);  
  3.         Student s1 = new Student(1,"ylf");  
  4.         Student s2 = new Student(2,"dsb");  
  5.         Student s3 = new Student(3,"dbc");  
  6.           
  7.         bDB.put(1, s1);  
  8.         bDB.put(2, s2);  
  9.         bDB.put(3, s3);  
  10.           
  11.         BDBIterator it = bDB.getIterator();  
  12.         Student s = null;  
  13.         int no=0;  
  14.         while(it.hasNext()){  
  15.               
  16.             s = (Student)it.currentValue();  
  17.             no = Integer.parseInt((String) it.currentKey());  
  18.             System.out.println("my name is "+s.getName()+" no is "+s.getNo()+" "+no);  
  19.         }  
  20.         while(it.hasPrev()){  
  21.               
  22.             s = (Student)it.currentValue();  
  23.             no = Integer.parseInt((String) it.currentKey());  
  24.             System.out.println("my name is "+s.getName()+" no is "+s.getNo()+" "+no);  
  25.         }  
  26.         it.close();  
  27.         BDBIterator it2 = bDB.getIterator();  
  28.         while(it2.hasNext()){  
  29.               
  30.             s = (Student)it2.currentValue();  
  31.             no = Integer.parseInt((String) it2.currentKey());  
  32.             System.out.println("my name is "+s.getName()+" no is "+s.getNo()+" "+no);  
  33.         }  
  34.         it2.close();  
  35.           
  36.         System.out.println(bDB.size());  
  37.           
  38.         s = bDB.find(2);  
  39.         System.out.println("find my name is "+s.getName());  
  40.           
  41.         bDB.close();  
  42.     }  

0 0
原创粉丝点击