初试DB4O

初试DB4O

面向对象的数据库,大致照着例子用了一下。要用好还要继续研究咯。
下载地址是:
http://www.db4o.com/
写了一个DEMO,DB4OService.java:
package com.sillycat.plugin.db4o;

import java.util.List;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectServer;
import com.db4o.query.Predicate;
import com.db4o.query.Query;
import com.sillycat.core.model.User;

public class DB4OService {

private ObjectContainer db;

private boolean isLocal = true;

public void init() {
   if (isLocal) {
    db = Db4o.openFile("local.yap");
   } else {
    ObjectServer server = Db4o.openServer("server.yap", 1212);
    server.grantAccess("sillycat", "kaishi");

    db = Db4o.openClient("192.168.10.103", 1212, "sillycat", "kaishi");
   }
}

public void destroy() {
   if (db != null) {
    db.close();
   }
}

public ObjectContainer getDB() {
   if (db == null) {
    init();
   }
   return db;
}

public static void main(String[] args) {
   DB4OService s = new DB4OService();
   s.init();
   ObjectContainer db = s.getDB();
   User u1 = new User();
   u1.setId(Integer.valueOf("1"));
   u1.setName("sillycat01");
   try {
    db.set(u1);
   } catch (Exception e) {
    s.destroy();
    e.printStackTrace();
   }

   // QBE(Query by Example)
   try {
    List lusers = db.get(u1);
    System.out.println(lusers.size() + " : " + lusers.get(0));
   } catch (Exception e) {
    s.destroy();
    e.printStackTrace();
   }
 
   // SODA(Simple Object Database Access)
   try {
    Query lquery = db.query();
    lquery.constrain(User.class);
    lquery.descend("name").constrain("sillycat01");
    List lusers2 = lquery.execute();
    System.out.println(lusers2.size() + " : " + lusers2.get(0));
   } catch (Exception e) {
    s.destroy();
    e.printStackTrace();
   }

   // NQ(Native Queries)
   try {
    List lusers3 = db.query(new Predicate<User>() {
     public boolean match(User u) {
      // 这样才是类型安全的
      return u.getName().equals("sillycat01");
     }
    });
    System.out.println(lusers3.size() + " : " + lusers3.get(0));
   } catch (Exception e) {
    s.destroy();
    e.printStackTrace();
   }
   db.delete(u1);
}
}

你可能感兴趣的:(Access)