六、BDB JE中對自定義對象的存儲

 使用tuple binding 來綁定自定義數據的步驟

1、 實例化你要存儲的對象
2、 通過com.sleepycat.bind.tuple.TupleBinding class來創建一個tuple binding。
3、 創建一個database,跟序列化的對象不同,你只需要創建一個。
4、 通過繼承第二步的類來創建一個entry binding 對象。
5、 存儲和使用數據

 

自定義對象:
public class Student {

 private int id;
 private String name;
 private int age;

//get()和set()方法

........
}

創建Tuple binding對象:

 

  1. public class StudentTupleBinging extends TupleBinding{ 
  2.  
  3.  @Override 
  4.  public Object entryToObject(TupleInput input) { 
  5.   int id=input.readInt(); 
  6.   String name=input.readString(); 
  7.   int age=input.readInt(); 
  8.   Student student=new Student(); 
  9.   student.setId(id); 
  10.   student.setName(name); 
  11.   student.setAge(age); 
  12.   return student; 
  13.  } 
  14.  
  15.  @Override 
  16.  public void objectToEntry(Object object, TupleOutput output) { 
  17.   Student student=(Student)object; 
  18.   output.writeInt(student.getId()); 
  19.   output.writeString(student.getName()); 
  20.   output.writeInt(student.getAge()); 
  21.  } 
  22.  
  23.  
  24. 存儲: 
  25.  
  26. public class StudentMainTwo { 
  27.  
  28.  private Environment myenv; 
  29.  private Database mydb; 
  30.  private TupleBinding studentBinding; 
  31.  
  32. //d://workspace//MyTest//src//test//student.txt中的文件內容爲 
  33.  
  34. /** 
  35.  * 1#Ashley#21 
  36. *2#bill#20 
  37. *3#skey#19 
  38. *4#Jessica#21 
  39. *5#Amanda#22 
  40. *6#Sarah#20 
  41. *7#Brittany#18 
  42. * 
  43.  
  44. */ 
  45.  private static File studentFile = new File("D://workspace//MyTest//src//test//student.txt"); 
  46.  private static DatabaseEntry theKey = new DatabaseEntry(); 
  47.  private static DatabaseEntry theData = new DatabaseEntry(); 
  48.  public static void main(String[] args) { 
  49.   StudentMainTwo studentMainTwo=new StudentMainTwo(); 
  50.   studentMainTwo.start("D://bdb"100000"student"); 
  51.   try { 
  52.    studentMainTwo.loadData(); 
  53.    studentMainTwo.showStudent(); 
  54.   } catch (Exception e) { 
  55.    e.printStackTrace(); 
  56.   } 
  57.  } 
  58.  
  59.  public void showStudent() throws DatabaseException { 
  60.   Cursor cursor = mydb.openCursor(nullnull); 
  61.   try { 
  62.    while (cursor.getNext(theKey, theData, LockMode.DEFAULT) == OperationStatus.SUCCESS) { 
  63.     Student stu1 = (Student) studentBinding.entryToObject(theData); 
  64.     System.out.println(stu1.getId() + "   " + stu1.getName() 
  65.       + "   " + stu1.getAge()); 
  66.    } 
  67.   } catch (Exception e) { 
  68.    System.err.println("Error on inventory cursor:"); 
  69.    System.err.println(e.toString()); 
  70.    e.printStackTrace(); 
  71.   } finally { 
  72.    cursor.close(); 
  73.   } 
  74.  } 
  75.  
  76.  public void loadData() throws DatabaseException { 
  77.   List<String[]> students = loadFile(studentFile, 8); 
  78.   studentBinding = new StudentTupleBinging(); 
  79.   //System.out.println(myenv.getConfig()); 
  80.   //Transaction txn = myenv.beginTransaction(null, null); 
  81.   for (int i = 0; i < students.size(); i++) { 
  82.    String[] student = students.get(i); 
  83.    try { 
  84.     theKey = new DatabaseEntry(student[0].getBytes("utf-8")); 
  85.     Student stu = new Student(); 
  86.     stu.setId(Integer.parseInt(student[0])); 
  87.     stu.setName(student[1]); 
  88.     stu.setAge(Integer.parseInt(student[2])); 
  89.     studentBinding.objectToEntry(stu, theData); 
  90.     mydb.put(null, theKey, theData); 
  91.    } catch (UnsupportedEncodingException e) { 
  92.     e.printStackTrace(); 
  93.    } 
  94.   } 
  95.  } 
  96.  
  97.  public void start(String filename, long cacheSize, String dbname) { 
  98.   EnvironmentConfig envconfig = new EnvironmentConfig(); 
  99.   envconfig.setAllowCreate(true); 
  100.   envconfig.setReadOnly(false); 
  101.   DatabaseConfig dbconfig = new DatabaseConfig(); 
  102.   dbconfig.setAllowCreate(true); 
  103.   dbconfig.setReadOnly(false); 
  104.   try { 
  105.    myenv = new Environment(new File(filename), envconfig); 
  106.    mydb = myenv.openDatabase(null, dbname, dbconfig); 
  107.   } catch (Exception e) { 
  108.    e.printStackTrace(); 
  109.   } 
  110.  } 
  111.  
  112.  private List<String[]> loadFile(File theFile, int numFields) { 
  113.   List<String[]> records = new ArrayList<String[]>(); 
  114.   try { 
  115.    String theLine = null
  116.    FileInputStream fis = new FileInputStream(theFile); 
  117.    BufferedReader br = new BufferedReader(new InputStreamReader(fis)); 
  118.    while ((theLine = br.readLine()) != null) { 
  119.     String[] theLineArray = theLine.split("#"); 
  120.     if (theLineArray.length != numFields) { 
  121.      System.out.println("Malformed line found in " 
  122.        + theFile.getPath()); 
  123.      System.out.println("Line was: '" + theLine); 
  124.      System.out.println("length found was: " 
  125.        + theLineArray.length); 
  126.      //System.exit(-1); 
  127.     } 
  128.     records.add(theLineArray); 
  129.    } 
  130.    // Close the input stream handle 
  131.    fis.close(); 
  132.   } catch (FileNotFoundException e) { 
  133.    System.err.println(theFile.getPath() + " does not exist."); 
  134.    e.printStackTrace(); 
  135.    usage(); 
  136.   } catch (IOException e) { 
  137.    System.err.println("IO Exception: " + e.toString()); 
  138.    e.printStackTrace(); 
  139.    System.exit(-1); 
  140.   } 
  141.   return records; 
  142.  } 
  143.  
  144.  private static void usage() { 
  145.   System.out.println("ExampleDatabasePut [-h <env directory>]"); 
  146.   System.out.println("      [-s <selections file>] [-v <vendors file>]"); 
  147.   System.exit(-1); 
  148.  } 
  149.  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章