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. Codeforces Gym101606 D.Deranging Hat (2017 United Kingdom and Ireland Programming Contest (UKIEPC 2017))

    D Deranging Hat 这个题简直了,本来想的是冒泡排序然后逆着输出来的,后来发现不对,因为题目上求的是最优解,而且冒泡的话,输出结果有的超出10000行了,所以就是把一开始的,排好序的字母标 ...

  2. FMDB使用Cached Statement功能

    FMDB使用Cached Statement功能   在FMDB中,Cached Statement功能是一种提高SQLite数据库访问的技术.在SQLite中,所有的SQL语句都会被编译,形成预处理 ...

  3. Codeforces Gym 100431D Bubble Sort 水题乱搞

    原题链接:http://codeforces.com/gym/100431/attachments/download/2421/20092010-winter-petrozavodsk-camp-an ...

  4. 转载cookie理解

    本文转自https://www.cnblogs.com/dojo-lzz/p/5580301.html 服务器端像客户端发送Cookie是通过HTTP响应报文实现的,在Set-Cookie中设置需要像 ...

  5. 132-pattern(蛮难的)

    https://leetcode.com/problems/132-pattern/ 下面是我的做法.后来又看了一个提示: https://discuss.leetcode.com/topic/678 ...

  6. Lucene的基本应用

    import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; ...

  7. 转: 如何选CDN:互联网大直播时代的CDN选择指南

    from:  http://www.chnvideo.com/blog-classic-cdn.html SRS 编码器   如何选CDN:互联网大直播时代的CDN选择指南 CDN是一个服务型的公司, ...

  8. AngularJS的ng-class示例

    程序下载:https://files.cnblogs.com/files/xiandedanteng/angularJSRender.rar 代码: <!DOCTYPE HTML PUBLIC ...

  9. JD笔试试题(凭记忆写的+人生感悟 try finally )

    京东笔试:技术篇(一套卷.包含測试.算法,研发) 一:填空题(4分 * 15) 15 个 涉及的面很广的选择题,可是比較側重基础.包含数据结构的.c++类的,操作系统的,计算机网络的. 二:编程题(2 ...

  10. Linux退出时出现there are stopped jobs如何解决?

    Linux 使用exit时出现there are stopped jobs如何解决? 这是因为一些命令被挂起了, 在后台驻留,需要关闭. 解决问题: 输入命令jobs -l显示停止进程的详细列表 可以 ...