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. C#知识点总结:Monitor和Lock以及区别

    Monitor对象 1.Monitor.Enter(object)方法是获取锁,Monitor.Exit(object)方法是释放锁,这就是Monitor最常用的两个方法,当然在使用过程中为了避免获取 ...

  2. 设计模式原来如此-策略模式(Strategy Pattern)

    策略模式中体现了两个非常基本的面向对象设计的原则:1.封装变化的概念.2.编程中使用接口,而不是对接口的实现. 策略模式的定义:定义一组算法,将每个算法都封装起来,并使它们之间可以互换.策略模式使这些 ...

  3. 使用vue-element-admin框架开发时遇到的跨域问题

    之前 使用js和jquery开发时也碰到过接口请求时的跨域问题, 但是在使用vue-element-admin开发也碰到这个问题,而且不能使用之前的方法解决,查过不少资料,找到一个很好的方法解决了这个 ...

  4. 最简单的window下使用Jenkins来做自动化部署的教程

    今天我们来说一下,如何使用Jenkins+powershell脚本,将我们的.NET CORE的脚本部署到对应的服务器上. 这里我们使用的源码管理工具是TFS.虽然源码管理器比较老旧,但是原理都差不多 ...

  5. Jenkins解决Host key verification failed

    1.在没有做任何操作时,是这样报错的 a.在任务中配置远程执行命令 rsync -raz --delete --progress  target/testweb-v1.1.jar  root@10.0 ...

  6. AC自动机(加强版)

    题目描述 有NN个由小写字母组成的模式串以及一个文本串TT.每个模式串可能会在文本串中出现多次.你需要找出哪些模式串在文本串TT中出现的次数最多. 输入输出格式 输入格式: 输入含多组数据. 每组数据 ...

  7. codeforces 979E(dp套dp)

    题意: 有n个点,编号为1~n.有的点颜色是黑色,有的点颜色是白色,有的点的颜色待涂.你还可以连一些边,但这些边一定是从小编号连到大编号的点. 对于一个确定的图,我们去统计有多少条路径满足“该路径经过 ...

  8. Dubbo zookeeper 初探

    先把zookeeper在本地给安装好, 安装方法参考:http://blog.csdn.net/wxwzy738/article/details/16330253 这里的话讲述了两个工程一个工程是提供 ...

  9. [MFC]选择目录对话框和选择文件对话框 [转]

      在MFC编程中经常会需要用到选择目录和选择文件的界面,以下总结一下本人常用的这两种对话框的生成方法: 选择目录对话框 {    char szPath[MAX_PATH];     //存放选择的 ...

  10. Keras学习

    参加比赛用到了keras,虽然之前用tensorflow,但是感觉tensorflow的确不太友好,api比较难读,然后就学习keras使用 随着深入,发现keras的api确实比较友好 跑了一些ex ...