JDBM2 提供了 HashMap 和 TreeMap 的磁盘存储功能,简单易用,用于持久化数据。特别适合用于嵌入到其他应用程序中。

磁盘数据库

HelloWorld.java

import java.io.IOException;

import jdbm.PrimaryTreeMap;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory; /**
* This program demonstrates basic JDBM usage.
*
* @author Jan Kotek
*
*/
public class HelloWorld {
public static void main(String[] args) throws IOException { /** create (or open existing) database */
String fileName = "helloWorld";
RecordManager recMan = RecordManagerFactory.createRecordManager(fileName); /** Creates TreeMap which stores data in database.
* Constructor method takes recordName (something like SQL table name)*/
String recordName = "firstTreeMap";
PrimaryTreeMap<Integer,String> treeMap = recMan.treeMap(recordName); /** add some stuff to map*/
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three"); System.out.println(treeMap.keySet());
// > [1, 2, 3] /** Map changes are not persisted yet, commit them (save to disk) */
recMan.commit(); System.out.println(treeMap.keySet());
// > [1, 2, 3] /** Delete one record. Changes are not commited yet, but are visible. */
treeMap.remove(2); System.out.println(treeMap.keySet());
// > [1, 3] /** Did not like change. Roolback to last commit (undo record remove). */
recMan.rollback(); /** Key 2 was recovered */
System.out.println(treeMap.keySet());
// > [1, 2, 3] /** close record manager */
recMan.close(); }
}

HelloWorld2.java

import java.io.IOException;
import java.io.Serializable; import jdbm.PrimaryStoreMap;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.SecondaryKeyExtractor;
import jdbm.SecondaryTreeMap; /**
* More advanced example to demonstrate Map usage.
*
* @author Jan Kotek
*
*/
public class HelloWorld2 { static class Person implements Serializable{ /** never forget this, very important for serialization*/
private static final long serialVersionUID = -3321252970661193623L;
final String name;
final String town;
final String country; /** some data to object class bigger */
final byte[] balast = new byte[1024]; public Person(String name, String town, String country) {
this.name = name;
this.town = town;
this.country = country;
} @Override
public String toString() {
return "Person [name=" + name + ", town=" + town + ", country=" + country + "]";
} /** snip getters and setters*/ } public static void main(String[] args) throws IOException {
RecordManager recman = RecordManagerFactory.
createRecordManager("HelloWorld2");
/**
* Create primary map which is used to store records.
* Data can be also stored in PrimaryTreeMap and PrimaryHashMap,
* but this is more efficient for large objects.
*/
PrimaryStoreMap<Long,Person> main = recman.storeMap("recman"); /**
* Create secondary index which points to Person name.
* SecondaryMap is readonly, it is updated by PrimaryMap.
*
* Secondary map have three types,
* first is type of secondary index (string),
* second and third are copied from primary map.
*/
SecondaryTreeMap<String, Long, Person> nameIndex = main.secondaryTreeMap("nameIndex",
new SecondaryKeyExtractor<String, Long, Person>() {
public String extractSecondaryKey(Long key, Person value) {
return value.name;
}
}); /**
* Another secondary map which points to town and country
*/
SecondaryTreeMap<String, Long, Person> townIndex = main.secondaryTreeMap("townIndex",
new SecondaryKeyExtractor<String, Long, Person>() {
public String extractSecondaryKey(Long key, Person value) {
/**
* Note format of map key
*/
return value.country+"/"+value.town;
}
}); /**
* And very simple index of Evil family members
*/
SecondaryTreeMap<Boolean, Long, Person> evilIndex = main.secondaryTreeMap("evilIndex",
new SecondaryKeyExtractor<Boolean, Long, Person>() {
public Boolean extractSecondaryKey(Long key, Person value) {
return value.name.contains("Evil");
}
}); /**
* Clean up, if this example was run more times.
* All secondary indexes are updated automatically.
*/
main.clear(); /**
* Add some data.
* StoreMap does not have usuall 'put' method.
* Key is generated by Store, so use 'putValue' instead
*/
main.putValue(new Person("James Bond","London","UK"));
main.putValue(new Person("Austin Powers","London","UK"));
main.putValue(new Person("Dr Evil","Vulcano Island","Ocean"));
main.putValue(new Person("Scott Evil","Vulcano Island","Ocean"));
main.putValue(new Person("Vanessa Kensington","London","UK"));
main.putValue(new Person("Alotta Fagina","Las Vegas","USA")); /**
* Persists inserted values
*/
recman.commit(); /**
* Get persons with name Austin Powers
*/
System.out.println();
System.out.println("Austin Powers: ");
for(Person person:nameIndex.getPrimaryValues("Austin Powers")){
System.out.println(" "+person);
} /**
* Print all Persons who lives on Vulcano Island.
* First we must obtain key from primary map,
* then
*/
System.out.println();
System.out.println("Persons on Vulcano Island: ");
for(Person person:townIndex.getPrimaryValues("Ocean/Vulcano Island")){
System.out.println(" "+person);
} /**
* Get everyone who is Evil
*/
System.out.println();
System.out.println("Evil family: ");
for(Person person:evilIndex.getPrimaryValues(true)){
System.out.println(" "+person);
} recman.close();
}
}

HugeData.java

import java.io.IOException;

import jdbm.PrimaryTreeMap;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory; /**
*
* This examples generates huge map of data.
* It inserts 10 000 000 records, it takes about 10 minutes to finish.
*
* @author Jan Kotek
*
*/
public class HugeData {
public static void main(String[] args) throws IOException { /** open db */
RecordManager recman = RecordManagerFactory.createRecordManager( "hugedata");
PrimaryTreeMap<Long, String> m = recman.treeMap("hugemap"); /** insert 1e7 records */
for(long i = 0;i<1e8;i++){
m.put(i, "aa"+i);
if(i%1e5==0){
/** Commit periodically, otherwise program would run out of memory */
recman.commit();
System.out.println(i);
} } recman.commit();
recman.close();
System.out.println("DONE"); }
}

Persons1.java

import java.io.IOException;
import java.io.Serializable; import jdbm.PrimaryTreeMap;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.SecondaryKeyExtractor;
import jdbm.SecondaryTreeMap; /**
* Demonstrates more advanced usage of JDBM:
* Secondary maps, 1:N relations.
*
* @author Jan Kotek
*
*/
public class Persons1 { static class Person implements Serializable{
/** field used for person identification (primary key)**/
String name;
/** persisted with Person (embedded field in JPA terms) **/
Address adress;
/** N:1 relation */
String fatherName; /** constructor, getters and setters are excluded for simplicity */
public Person(String name, Address adress,String fatherName) {
super();
this.name = name;
this.adress = adress;
this.fatherName = fatherName;
} public String toString(){
return "Person["+name+"]";
} public int hashCode() {
return name == null? 0 : name.hashCode();
} public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof Person))
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} } static class Address implements Serializable{
String streetName;
String town;
String country; public Address(String streetName, String town, String country) {
super();
this.streetName = streetName;
this.town = town;
this.country = country;
} } public static void main(String[] args) throws IOException {
//init Record Manager and dao
RecordManager recman = RecordManagerFactory.createRecordManager("persons1"); PrimaryTreeMap<String,Person> personsByName = recman.treeMap("personsByName"); SecondaryTreeMap<String, String, Person> personsByTown =
personsByName.secondaryTreeMap("personsByTown",
new SecondaryKeyExtractor<String, String, Person>() {
public String extractSecondaryKey(String key,Person value) {
return value.adress.town;
}
}); //create a few persons
Person patrick = new Person("Patrick Moore",
new Address("First street", "Athlone","Ireland"),
null);
personsByName.put(patrick.name, patrick); Person jack = new Person("Jack Moore",
new Address("First street", "Athlone","Ireland"),
patrick.name);
personsByName.put(jack.name, jack); Person paul = new Person("Paul Moore",
new Address("Shop street", "Galway","Ireland"),
patrick.name);
personsByName.put(paul.name, paul ); System.out.println("Number of persons: "+personsByName.size()); System.out.println("Persons with name Patrick Moore: "+personsByName.get("Patrick Moore"));
System.out.println("Name of persons living in Galway: "+personsByTown.get("Galway"));
System.out.println("Father of Paul Moore: "+
personsByName.get(
personsByName.get("Paul Moore").fatherName
)); } }

Persons2.java

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import jdbm.InverseHashView;
import jdbm.PrimaryStoreMap;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.SecondaryKeyExtractor;
import jdbm.SecondaryTreeMap;
import jdbm.Serializer;
import jdbm.SerializerInput;
import jdbm.SerializerOutput;
import jdbm.helper.Serialization; /**
* Demonstrates more advanced usage of JDBM:
* Secondary maps, 1:N relations.
*
* @author Jan Kotek
*
*/
public class Persons2 { static class Person implements Serializable{
/** field used for person identification (primary key)**/
String name;
/** persisted with Person (embedded field in JPA terms) **/
Address adress;
/** N:1 relation */
Person father; /** constructor, getters and setters are excluded for simplicity */
public Person(String name, Address adress,Person father) {
super();
this.name = name;
this.adress = adress;
this.father = father;
} public String toString(){
return "Person["+name+"]";
} public int hashCode() {
return name == null? 0 : name.hashCode();
} public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof Person))
return false;
Person other = (Person) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} } static class Address implements Serializable{
String streetName;
String town;
String country; public Address(String streetName, String town, String country) {
super();
this.streetName = streetName;
this.town = town;
this.country = country;
} } /** dao object which handles Person persistence */
static class PersonDao implements Serializer<Person>{ /**
* This is map in which persons are inserted in.
* Key is number assigned by store (recordId).
* You should prefer recordId as primary index, it is more flexible.
*/
PrimaryStoreMap<Long,Person> persons; /** Inverse view on person, it helps to find recordId which belongs to person */
InverseHashView< Long, Person> personsInverse; /**
* Secondary view on persons, which identifies person by name.
* This map is readonly, it is autoupdated by JDBM as primary map changes.
* Key is name, value is recordId ( key from primary map),
* third parameter is Person (value from primary map)
*/
SecondaryTreeMap<String, Long, Person> personsByName; /**
* Secondary view on persons, which identifies person its town
* This map is readonly, it is autoupdated by JDBM as primary map changes.
* Key is town name extracted from primary table,
* value is recordId ( key from primary map),
* third parameter is town from (value from primary map)
*/
SecondaryTreeMap<String, Long, Person> personsByTown; public PersonDao(RecordManager recman) {
persons = recman.storeMap("persons",this);
personsInverse = persons.inverseHashView("personsInverse");
personsByName = persons.secondaryTreeMap("personsByName",
new SecondaryKeyExtractor<String, Long, Person>() {
public String extractSecondaryKey(Long key, Person value) {
return value.name;
}});
personsByTown = persons.secondaryTreeMap("personsByTown",
new SecondaryKeyExtractor<String, Long, Person>() {
public String extractSecondaryKey(Long key, Person value) {
if(value.adress == null)
return null;
return value.adress.town;
}}); } public Person personByRecordId(Long recid){
return persons.get(recid);
} public Person personByName(String name){
if(!personsByName.containsKey(name))
return null;
Iterator<Long> iter = personsByName.get(name).iterator();
if(iter.hasNext())
return personsByName.getPrimaryValue(iter.next());
else
return null;
} public Iterable<Person> personsByTown(String name){
List<Person> ret = new ArrayList<Person>();
for(Long l: personsByTown.get(name)){
ret.add(personsByTown.getPrimaryValue(l));
}
return ret;
} public void insertPerson(Person person){
Long recid = personsInverse.findKeyForValue(person);
if(recid == null)
persons.putValue(person);
else
persons.put(recid, person);
} public Person deserialize(SerializerInput in) throws IOException, ClassNotFoundException {
String name = in.readObject();
Address address = in.readObject();
Person father = persons.get(in.readObject());
Person p = new Person(name,address,father); return p;
} public void serialize(SerializerOutput out, Person obj)
throws IOException {
out.writeObject(obj.name);
out.writeObject(obj.adress);
out.writeObject(findOrPersistPerson(obj.father));
} protected Long findOrPersistPerson(Person person){
if(person == null)
return null;
Long recid = personsInverse.findKeyForValue(person);
if(recid == null)
recid = persons.putValue(person);
return recid;
} } public static void main(String[] args) throws IOException {
//init Record Manager and dao
RecordManager recman = RecordManagerFactory.createRecordManager("persons2");
PersonDao dao = new PersonDao(recman); //create a few persons
Person patrick = new Person("Patrick Moore",
new Address("First street", "Athlone","Ireland"),
null); Person jack = new Person("Jack Moore",
new Address("First street", "Athlone","Ireland"),
patrick); Person paul = new Person("Paul Moore",
new Address("Shop street", "Galway","Ireland"),
patrick); //now store all this stuff
dao.insertPerson(jack);
dao.insertPerson(patrick);
dao.insertPerson(paul); System.out.println("Number of persons: "+dao.persons.size()); System.out.println("Persons with name Patrick Moore: "+dao.personByName("Patrick Moore"));
System.out.println("Persons living in Galway: "+dao.personsByTown("Galway"));
System.out.println("Father of Paul Moore: "+dao.personByName("Paul Moore").father); } }

java JDBM2 的几个简单实例的更多相关文章

  1. Java解析XML文档(简单实例)——dom解析xml

      一.前言 用Java解析XML文档,最常用的有两种方法:使用基于事件的XML简单API(Simple API for XML)称为SAX和基于树和节点的文档对象模型(Document Object ...

  2. java操作mongoDB数据库的简单实例

    首先导入mongoDB的jar包 http://pan.baidu.com/s/1bnGMJRD //DataBase.java package com.mongodb.test; import ja ...

  3. java自动生成表单简单实例

    数据库表设置 tb_form(form表单) 字段 类型 约束 说明 Id Int 主键 主键 Formid Varchar2(20) 唯一 Form表单id的值 Action Varchar2(20 ...

  4. JAVA 几种多线程的简单实例 Thread Runnable

    实例1: class Hello extends Thread{ private String name; public Hello(){} public Hello(String name){ th ...

  5. 主题:Java WebService 简单实例

    链接地址:主题:Java WebService 简单实例    http://www.iteye.com/topic/1135747 前言:朋友们开始以下教程前,请先看第五大点的注意事项,以避免不必要 ...

  6. java反射机制简单实例

    目录 Java反射 简单实例 @(目录) Java反射 Java语言允许通过程序化的方式间接对Class进行操作.Class文件由类装载器装载后,在JVM中将形成一份描述Class结构的元信息对象,通 ...

  7. JAVA RMI远程方法调用简单实例[转]

    RMI的概念 RMI(Remote Method Invocation)远程方法调用是一种计算机之间利用远程对象互相调用实现双方通讯的一种通讯机制.使用这种机制,某一台计算机上的对象可以调用另外 一台 ...

  8. JAVA RMI远程方法调用简单实例(转载)

    来源:http://www.cnblogs.com/leslies2/archive/2011/05/20/2051844.html RMI的概念 RMI(Remote Method Invocati ...

  9. Hibernate(二)__简单实例入门

    首先我们进一步理解什么是对象关系映射模型? 它将对数据库中数据的处理转化为对对象的处理.如下图所示: 入门简单实例: hiberante 可以用在 j2se 项目,也可以用在 j2ee (web项目中 ...

随机推荐

  1. AC日记——[JLOI2014]松鼠的新家 洛谷 P3258

    题目描述 松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的.天哪,他居然真的住在”树“上. 松鼠想邀请小熊维尼前 ...

  2. 腾讯IM的那些坑

    项目中接入腾讯IM,在这里记录下,以便大家解决问题时少走弯路 1.首先讲一下IM返回对象的问题: /** * 消息工厂方法 */ public static Message getMessage(TI ...

  3. HDU 5733 tetrahedron(计算几何)

    题目链接 tetrahedron 题目大意 输入一个四面体求其内心,若不存在内心则输出"O O O O" 解题思路 其实这道题思路很简单,只要类推一下三角形内心公式就可以了. 至于 ...

  4. 邁向IT專家成功之路的三十則鐵律 鐵律九:IT人社群互動之道-縮小自己

    身為一位專業的IT人士所要學習的東西實在非常的多,然而對於時間相當有限的我們,最快速的學習方法就是向他人學習,而向他人學習的首要態度就是「縮小自己」.唯有將自己縮小到別人的眼睛裡,才能夠讓他們真心誠意 ...

  5. PhantomJS 基础及示例 (转)

    概述 PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support f ...

  6. GO --微服务框架(二) goa

    之前用过go语言的反射来做一些代码生成,参考这篇. 但是这种方式,入侵太强,需要执行对应的申明调用, 所以对GOA框架的自动生成非常感兴趣,于是仔细研究了一下,发现用的比较巧妙, 这里先卖个关子,先看 ...

  7. 【Nginx】事件驱动框架和异步处理

    Nginx对请求的处理是通过事件触发的,模块作为事件消费者,仅仅能被事件收集.分发器调用.这与传统的Webserver是不同的. 传统的Webserver下,一个请求由一个进程消费.请求在建立连接后将 ...

  8. 反射 type 的基本用法,动态加载插件

    这里介绍反射的简单实用 MyClass类 public class MyClass { public int Age { get; set; } public string Name { get; s ...

  9. 自己定义ImageView,实现点击之后算出点击的是身体的哪个部位

    近期也是由于项目的原因,所以有机会接触到这边的算法. 此文重点不是怎样实现的思路和原理, 有须要的同事能够借鉴一下 废话不多说,直接上代码: <span style="font-siz ...

  10. Python+Selenium ----unittest单元测试框架

    unittest是一个单元测试框架,是Python编程的单元测试框架.有时候,也做叫做“PyUnit”,是Junit的Python语言版本.这里了解下,Junit是Java语言的单元测试框架,Java ...