db4o_8.0对象数据库官方文档翻译_学习笔记二

紧接上篇:db4o_8.0对象数据库官方文档翻译_学习笔记一

2. First Steps(第一步)

Let's get started as simple as possible. We are going to demonstrate how to store, retrieve, update and delete instances of a single class that only contains primitive and String members. In our example this will be a Formula One (F1) pilot whose attributes are his name and the F1 points he has already gained this season.

让我们尽量简单地开始。我们将演示用db4o如何存储,读取,更新和删除一个类的实例,这个类只包含基本类型和String类型的成员变量。在我们的例子中就是F1飞行员的名字和他在这个赛季获的得分。

First we create a class to hold our data. It looks like this:

首先创建一个类来保存我们的数据。代码示例如下:

package bo;

 

public class Pilot {

private String name;

private int points;

 

public Pilot(String name, int points) {

this.name = name;

this.points = points;

}

 

public int getPoints() {

return points;

}

 

public void addPoints(int points) {

this.points += points;

}

 

public String getName() {

return name;

}

 

public String toString() {

return name + "/" + points;

}

}

Notice that this class does not contain any db4o-related code.

注意这个类中没有包含任何和db4o有关的代码。

 

2.1. Opening the database

To access a db4o database file or create a new one, call Db4oEmbedded.openFile() and provide Db4oEmbedded.newConfiguration() as a configuration template and the path to your database file as the second parameter, to obtain an ObjectContainer instance. ObjectContainer represents "The Database", and will be your primary interface to db4o. Closing the ObjectContainer with the #close() method will close the database file and release all resources associated with it.

要访问或新建一个db4o数据库文件,调用Db4oEmbedded.openFile() 并且提供Db4oEmbedded.newConfiguration() 作为配置模版即第一个参数,你的数据库路径作为第二个参数,来获得一个ObjectContainer 实例。ObjectContainer 就代表"数据库"。它将是你操作db4o的主要接口。调用#close()方法来关闭ObjectContainer,这样作也将关闭数据库文件并且释放所有关联的资源。

// accessDb4o

ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded

.newConfiguration(), DB4OFILENAME);

try {

// do something with db4o

} finally {

db.close();

}

 

DB4OFILENAME is just a string value representing any filename. If the file with this name already exists, it will be opened as db4o database, otherwise a new db4o database will be created. For the following examples we will assume that our environment takes care of opening and closing the ObjectContainer automagically, and stores the reference in a variable named 'db'.

DB4OFILENAME 是一个代表任何文件名的字符串(常量),如果这个文件名已经存在,它将以db4o数据库的形式打开,否则,它将以该名字创建一个db4o数据库。在接下来的实例中,我们将假定由环境来自动管理ObjectContainer的打开,关闭,以'db'为变量名保存其引用。

2.2. Storing objects(保存对象)

To store an object, we simply call #store() on our database, passing any object as a parameter.

要保存对象,只需在数据库上调用store()方法,以任意对象为参数传入即可。

// storeFirstPilot

Pilot pilot1 = new Pilot("Michael Schumacher", 100);

db.store(pilot1);

System.out.println("Stored " + pilot1);

 

OUTPUT:

Stored Michael Schumacher/100

 

We'll need a second pilot, too.

我们接下来保存第二个对象:

// storeSecondPilot

Pilot pilot2 = new Pilot("Rubens Barrichello", 99);

db.store(pilot2);

System.out.println("Stored " + pilot2);

 

OUTPUT:

Stored Rubens Barrichello/99

 

2.3. Retrieving objects (检索对象)

The easiest way to see the content of our database is to use Object Manager Enterprise, which will be introduced in the next chapter . For now let's continue with the API overview and learn how to build db4o queries.

db4o supplies several different querying systems, Query by Example (QBE), , Native Queries (NQ) and the SODA Query API (SODA). In this first example we will introduce QBE. Once you are familiar with storing objects, we encourage you to use Native Queries .

When using Query-By-Example, you create a prototypical object for db4o to use as an example of what you wish to retrieve. db4o will retrieve all objects of the given type that contain the same (nondefault) field values as the example. The results will be returned as an ObjectSet instance. We will use a convenience method #listResult() to display the contents of our result ObjectSet :

查看数据库内容最简单的方式就是使用下个章节我们要介绍的OME工具,现在,我们继续用API,并学习怎么建立db4o查询。

Db4o提供几种不同的查询机制,样本查询(QBE),原生查询(NQ)SODA查询接口(SODA)。在第一个例子中我们将介绍如何使用QBE。如果你对存储对象比较熟悉,我们推荐你使用本地查询(它是db4o主要的查询接口)。

在使用QBE时,你要创建一个原型对象作为你检索对象的样本。db4o会读取所有指定类型的对象,这些对像含有与样本一样(并非缺省)的属性值。结果以ObjectSet实例的形式返回。我们将使用一个便捷的方法#listResult()来显示查询结果对象集中的内容。

public static void listResult(List<?> result) {

System.out.println(result.size());

for (Object o : result) {

System.out.println(o);

}

}

 

To retrieve all pilots from our database, we provide an 'empty' prototype:

要从我们的数据库中检索所有的pilots,我们需要提供一个空的原型对象:

// retrieveAllPilotQBE

Pilot proto = new Pilot(null, 0);

ObjectSet result = db.queryByExample(proto);

listResult(result);

 

OUTPUT:

2

Michael Schumacher/100

Rubens Barrichello/99

Note that we specify 0 points, but our results were not constrained to only those Pilots with 0 points; 0 is the default value for int fields.

注意我们设定分数为0,但是我们的查询结果并没有受此约束,因为0int类型的缺省值。

 

db4o also supplies a shortcut to retrieve all instances of a class:

db4o还提供一个快捷方式来获取一个类的所有实例:

// retrieveAllPilots

ObjectSet result = db.queryByExample(Pilot.class);

listResult(result);

 

OUTPUT:

2

Michael Schumacher/100

Rubens Barrichello/99

 

For JDK 5 there also is a generics shortcut, using the query method:

JDK5也有一个泛型快捷方式,这样使用query方法:

 

List <Pilot> pilots = db.query(Pilot.class);

To query for a pilot by name:

通过名字查询赛车手,代码如下:

// retrievePilotByName

Pilot proto = new Pilot("Michael Schumacher", 0);

ObjectSet result = db.queryByExample(proto);

listResult(result);

 

OUTPUT:

1

Michael Schumacher/100

 

And to query for Pilots with a specific number of points:

使用给定的分数查询赛车手,代码如下:

// retrievePilotByExactPoints

Pilot proto = new Pilot(null, 100);

ObjectSet result = db.queryByExample(proto);

listResult(result);

OUTPUT:

1

Michael Schumacher/100

Of course there's much more to db4o queries. They will be covered in more depth in later chapters.

当然db4o有很多种查询方式,我们将会在后续的章节中深入学习。

 

2.4. Updating objects(更新对象)

Updating objects is just as easy as storing them. In fact, you use the same #store() method to update your objects: just call #store() again after modifying any object.

更新对象和存储对象一样容易,实际上,你使用相同的store()方法去更新你的对象,在你修改任何对象后只需要再次调用store就可以了。

// updatePilot

ObjectSet result = db

.queryByExample(new Pilot("Michael Schumacher", 0));

Pilot found = (Pilot) result.next();

found.addPoints(11);

db.store(found);

System.out.println("Added 11 points for " + found);

retrieveAllPilots(db);

 

OUTPUT:

Added 11 points for Michael Schumacher/111

2

Michael Schumacher/111

Rubens Barrichello/99

Notice that we query for the object first. This is an importaint point. When you call #store() to modify a stored object, if the object is not 'known' (having been previously stored or retrieved during the current session), db4o will insert a new object. db4o does this because it does not automatically match up objects to be stored, with objects previously stored. It assumes you are inserting a second object which happens to have the same field values. To make sure you've updated the pilot, please return to any of the retrieval examples above and run them again.

注意我们先查询得到要更新的对象,这点非常重要。当你调用store()去修改一个已经存储的对象时,如果这个对象不是持久化对象(在前面已经存储过或者在当前会话中读取到的对象),db4o将会插入一个新对象。db4o这么做是因为它不会自动比较要存储的对象和先前存储过的对象。它认为你是想再存储一个属性值一样的对象。要确认pilot是否更新成功,请找到前面的任何一段读取的示例程序再运行一次即可。

 

2.5. Deleting objects(删除对象)

Objects are removed from the database using the #delete() method.

从数据库删除对象用delete()方法

 

// deleteFirstPilotByName

ObjectSet result = db

.queryByExample(new Pilot("Michael Schumacher", 0));

Pilot found = (Pilot) result.next();

db.delete(found);

System.out.println("Deleted " + found);

retrieveAllPilots(db);

 

OUTPUT:

Deleted Michael Schumacher/111

1

Rubens Barrichello/99

 

Let's delete the other one, too.

让我们再删除掉另一个对照。

 

// deleteSecondPilotByName

ObjectSet result = db

.queryByExample(new Pilot("Rubens Barrichello", 0));

Pilot found = (Pilot) result.next();

db.delete(found);

System.out.println("Deleted " + found);

retrieveAllPilots(db);

 

OUTPUT:

Deleted Rubens Barrichello/99

0

 

Please check the deletion with the retrieval examples above.

As with updating objects, the object to be deleted has to be 'known' to db4o. It is not sufficient to provide a prototype object with the same field values.

运行前面读取的例子来验证删除是否成功。

和更新对象一样,要删除的对象也必须是持久对象,并且只是提供一个属性值一样的对象是不可以成功删除的。

2.6. Conclusion(总结)

That was easy, wasn't it? We have stored, retrieved, updated and deleted objects with a few lines of code. Now you are probably interested to see how the database looks like. Let's have a look using db4o graphical tool - Object Manager in the next chapter .

是不是很简单呀?我们只需要简单的几行代码就可以存储,读取,更新和删除对象。现在你可能对数据库是什么样充满了兴趣,我们用db4o的图形化工具(下单要讲的OM)便可查看。

2.7. Full source(所有源代码)

package bo.result;

 

import java.io.File;

import java.util.List;

 

import bo.Pilot;

 

import com.db4o.Db4oEmbedded;

import com.db4o.ObjectContainer;

import com.db4o.ObjectSet;

 

public class FirstStepsExample {

public static void listResult(List<?> result) {

System.out.println(result.size());

for (Object o : result) {

System.out.println(o);

}

}

final static String DB4OFILENAME = System.getProperty("user.home")

"/formula1.db4o";

 

public static void main(String[] args) {

new File(DB4OFILENAME).delete();

accessDb4o();

new File(DB4OFILENAME).delete();

ObjectContainer db = Db4oEmbedded.openFile(

Db4oEmbedded.newConfiguration(), DB4OFILENAME);

try {

storeFirstPilot(db);

storeSecondPilot(db);

retrieveAllPilots(db);

retrievePilotByName(db);

retrievePilotByExactPoints(db);

updatePilot(db);

deleteFirstPilotByName(db);

deleteSecondPilotByName(db);

finally {

db.close();

}

}

 

public static void accessDb4o() {

ObjectContainer db = Db4oEmbedded.openFile(

Db4oEmbedded.newConfiguration(), DB4OFILENAME);

try {

// do something with db4o

finally {

db.close();

}

}

 

public static void storeFirstPilot(ObjectContainer db) {

Pilot pilot1 = new Pilot("Michael Schumacher", 100);

db.store(pilot1);

System.out.println("Stored " + pilot1);

}

 

public static void storeSecondPilot(ObjectContainer db) {

Pilot pilot2 = new Pilot("Rubens Barrichello", 99);

db.store(pilot2);

System.out.println("Stored " + pilot2);

}

 

public static void retrieveAllPilotQBE(ObjectContainer db) {

Pilot proto = new Pilot(null, 0);

ObjectSet result = db.queryByExample(proto);

listResult(result);

}

 

public static void retrieveAllPilots(ObjectContainer db) {

ObjectSet result = db.queryByExample(Pilot.class);

listResult(result);

}

 

public static void retrievePilotByName(ObjectContainer db) {

Pilot proto = new Pilot("Michael Schumacher", 0);

ObjectSet result = db.queryByExample(proto);

listResult(result);

}

 

public static void retrievePilotByExactPoints(ObjectContainer db) {

Pilot proto = new Pilot(null, 100);

ObjectSet result = db.queryByExample(proto);

listResult(result);

}

 

public static void updatePilot(ObjectContainer db) {

ObjectSet result = db

.queryByExample(new Pilot("Michael Schumacher", 0));

Pilot found = (Pilot) result.next();

found.addPoints(11);

db.store(found);

System.out.println("Added 11 points for " + found);

retrieveAllPilots(db);

}

 

public static void deleteFirstPilotByName(ObjectContainer db) {

ObjectSet result = db

.queryByExample(new Pilot("Michael Schumacher", 0));

Pilot found = (Pilot) result.next();

db.delete(found);

System.out.println("Deleted " + found);

retrieveAllPilots(db);

}

 

public static void deleteSecondPilotByName(ObjectContainer db) {

ObjectSet result = db

.queryByExample(new Pilot("Rubens Barrichello", 0));

Pilot found = (Pilot) result.next();

db.delete(found);

System.out.println("Deleted " + found);

retrieveAllPilots(db);

}

}

db4o_8.0对象数据库官方文档翻译_学习笔记三http://blog.csdn.net/oceans521/article/details/43195809

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值