| |
处理多样性关系
舒适的家庭生活会导致一个或更多 “小人儿” 降临到这个家庭。但是,在增加小孩到家庭中之前,先确保 person 真正有地方可住。给他们一个工作场所,或者还有一个很好的夏日度假屋。一个 address 类型应该可以解决所有这三个地方。
清单 1. 添加一个 address 类型到 person 类中
package com.tedneward.model;
public class address { public address() { }
public address(string street, string city, string state, string zip) { this.street = street; this.city = city; this.state = state; this.zip = zip; }
public string tostring() { return "[address: " + "street=" + street + " " + "city=" + city + " " + "state=" + state + " " + "zip=" + zip + "]"; }
public int hashcode() { return street.hashcode() & city.hashcode() & state.hashcode() & zip.hashcode(); }
public boolean equals(object obj) { if (obj == this) return this;
if (obj instanceof address) { address rhs = (address)obj;
return (this.street.equals(rhs.street) && this.city.equals(rhs.city) && this.state.equals(rhs.state) && this.zip.equals(rhs.zip)); } else return false; }
public string getstreet() { return this.street; } public void setstreet(string value) { this.street = value; }
public string getcity() { return this.city; } public void setcity(string value) { this.city = value; }
public string getstate() { return this.state; } public void setstate(string value) { this.state = value; }
public string getzip() { return this.zip; } public void setzip(string value) { this.zip = value; }
private string street; private string city; private string state; private string zip; }
可以看到,address 只是一个简单的数据对象。将它添加到 person 类中意味着 person 将有一个名为 addresses 的 address 数组作为字段。第一个地址是家庭住址,第二个是工作地址,第三个(如果不为 null 的话)是度假屋地址。当然,这些都被设置为 protected,以便将来通过方法来封装。
完成这些设置后,现在可以增强 person 类,使之支持小孩,所以为 person 定义一个新字段:一个 person arraylist,它同样也有一些相关的方法,以便进行适当的封装。
接下来,由于大多数小孩都有父母,还将添加两个字段来表示母亲和父亲,并增加适当的 accessor/mutator 方法。将为 person 类增加一个新的方法,使之可以创建一个新的 person,这个方法有一个贴切的名称,即 havebaby。此外还增加一些业务规则,以支持生小孩的生物学需求,并将这个新的小 person 添加到为母亲和父亲字段创建的 children arraylist 中。做完这些之后,再将这个婴儿返回给调用者。
清单 2 显示,新定义的 person 类可以处理这种多样性关系。
清单 2. 定义为多样性关系的家庭生活
package com.tedneward.model;
import java.util.list; import java.util.arraylist; import java.util.iterator;
public class person { public person() { } public person(string firstname, string lastname, gender gender, int age, mood mood) { this.firstname = firstname; this.lastname = lastname; this.gender = gender; this.age = age; this.mood = mood; }
public string getfirstname() { return firstname; } public void setfirstname(string value) { firstname = value; }
public string getlastname() { return lastname; } public void setlastname(string value) { lastname = value; }
public gender getgender() { return gender; }
public int getage() { return age; } public void setage(int value) { age = value; }
public mood getmood() { return mood; } public void setmood(mood value) { mood = value; }
public person getspouse() { return spouse; } public void setspouse(person value) { // a few business rules if (spouse != null) throw new illegalargumentexception("already married!");
if (value.getspouse() != null && value.getspouse() != this) throw new illegalargumentexception("already married!");
spouse = value;
// highly sexist business rule if (gender == gender.female) this.setlastname(value.getlastname());
// make marriage reflexive, if its not already set that way if (value.getspouse() != this) value.setspouse(this); }
public address gethomeaddress() { return addresses[0]; } public void sethomeaddress(address value) { addresses[0] = value; }
public address getworkaddress() { return addresses[1]; } public void setworkaddress(address value) { addresses[1] = value; }
public address getvacationaddress() { return addresses[2]; } public void setvacationaddress(address value) { addresses[2] = value; }
public iterator<person> getchildren() { return children.iterator(); } public person havebaby(string name, gender gender) { // business rule if (this.gender.equals(gender.male)) throw new unsupportedoperationexception("biological impossibility!");
// another highly objectionable business rule if (getspouse() == null) throw new unsupportedoperationexception("ethical impossibility!");
// welcome to the world, little one! person child = new person(name, this.lastname, gender, 0, mood.cranky); // well, wouldnt you be cranky if youd just been pushed out of // a nice warm place?!?
// these are your parents... child.father = this.getspouse(); child.mother = this;
// ... and youre their new baby. // (everybody say "awwww....") children.add(child); this.getspouse().children.add(child);
return child; }
public string tostring() { return "[person: " + "firstname = " + firstname + " " + "lastname = " + lastname + " " + "gender = " + gender + " " + "age = " + age + " " + "mood = " + mood + " " + (spouse != null ? "spouse = " + spouse.getfirstname() + " " : "") + "]"; }
public boolean equals(object rhs) { if (rhs == this) return true;
if (!(rhs instanceof person)) return false;
person other = (person)rhs; return (this.firstname.equals(other.firstname) && this.lastname.equals(other.lastname) && this.gender.equals(other.gender) && this.age == other.age); }
private string firstname; private string lastname; private gender gender; private int age; private mood mood; private person spouse; private address[] addresses = new address[3]; private list<person> children = new arraylist<person>(); private person mother; private person father; }
即使包括所有这些代码,清单 2 提供的家庭关系模型还是过于简单。在这个层次结构中的某些地方,必须处理那些 null 值。但是,在 db4o 中,那个问题更应该在对象建模中解决,而不是在对象操作中解决。所以现在我可以放心地忽略它。
填充和测试对象模型
对于清单 2 中的 person 类,需要重点注意的是,如果以关系的方式,使用父与子之间分层的、循环的引用来建模,那肯定会比较笨拙。通过一个实例化的对象模型可以更清楚地看到我所谈到的复杂性,所以我将编写一个探察测试来实例化 person 类。注意,清单 3 中省略了 junit 支架(scaffolding)。
清单 3. 幸福家庭测试
@test public void testthemodel() { person bruce = new person("bruce", "tate", gender.male, 29, mood.happy); person maggie = new person("maggie", "tate", gender.female, 29, mood.happy); bruce.setspouse(maggie);
person kayla = maggie.havebaby("kayla", gender.female);
person julia = maggie.havebaby("julia", gender.female);
asserttrue(julia.getfather() == bruce); asserttrue(kayla.getfather() == bruce); asserttrue(julia.getmother() == maggie); asserttrue(kayla.getmother() == maggie);
int n = 0; for (iterator<person> kids = bruce.getchildren(); kids.hasnext(); ) { person child = kids.next();
if (n == 0) asserttrue(child == kayla); if (n == 1) asserttrue(child == julia);
n++; } }
目前一切尚好。所有方面都能通过测试,包括小孩 arraylist 的使用中的长嗣身份。但是,当增加 @before 和 @after 条件,以便用我的测试数据填充 db4o 数据库时,事情开始变得更有趣。
清单 4. 将孩子发送到数据库
@before public void preparedatabase() { db = db4o.openfile("persons.data");
person bruce = new person("bruce", "tate", gender.male, 29, mood.happy); person maggie = new person("maggie", "tate", gender.female, 29, mood.happy); bruce.setspouse(maggie);
bruce.sethomeaddress( new address("5 maple drive", "austin", "tx", "12345")); bruce.setworkaddress( new address("5 maple drive", "austin", "tx", "12345")); bruce.setvacationaddress( new address("10 wanahokalugi way", "oahu", "ha", "11223"));
person kayla = maggie.havebaby("kayla", gender.female); kayla.setage(8);
person julia = maggie.havebaby("julia", gender.female); julia.setage(6);
db.set(bruce);
db.commit(); }
注意,存储整个家庭所做的工作仍然不比存储单个 person 对象所做的工作多。您可能还记得,在上一篇文章中,由于存储的对象具有递归的性质,当把 bruce 引用传递给 db.set() 调用时,从 bruce 可达的所有对象都被存储。不过眼见为实,让我们看看当运行那个简单的探察测试时,实际上会出现什么情况。首先,测试当调用随 person 存储的各种 address 时,是否可以找到它们。然后,测试是否孩子们也被存储。
清单 5. 搜索住房和家庭
@test public void testthestorageofaddresses() { list<person> maletates = db.query(new predicate<person>() { public boolean match(person candidate) { return candidate.getlastname().equals("tate") && candidate.getgender().equals(gender.male); } }); person bruce = maletates.get(0);
address homeandwork = new address("5 maple drive", "austin", "tx", "12345"); address vacation = new address("10 wanahokalugi way", "oahu", "ha", "11223");
asserttrue(bruce.gethomeaddress().equals(homeandwork)); asserttrue(bruce.getworkaddress().equals(homeandwork)); asserttrue(bruce.getvacationaddress().equals(vacation)); }
@test public void testthestorageofchildren() { list<person> maletates = db.query(new predicate<person>() { public boolean match(person candidate) { return candidate.getlastname().equals("tate") && candidate.getgender().equals(gender.male); } }); person bruce = maletates.get(0);
int n = 0; for (iterator<person> children = bruce.getchildren(); children.hasnext(); ) { person child = children.next();
system.out.println(child);
if (n==0) asserttrue(child.getfirstname().equals("kayla")); if (n==1) asserttrue(child.getfirstname().equals("julia"));
n++; } }
理解关系
您可能会感到奇怪,清单 5 中显示的基于 collection 的类型(arraylist)没有被存储为 person 类型的 “dependents”,而是被存储为一个成熟的对象。这还说得过去,但是当对对象数据库中的 arraylist 运行一个查询时,它可能,有时候也确实会导致返回奇怪的结果。由于目前数据库中只有一个 arraylist,所以还不值得运行一个探察测试,看看当对它运行一个查询时会出现什么情况。把这作为留给您的练习。
自然地,存储在一个集合中的 person 也被当作数据库中的一级实体,所以在查询符合某个特定标准(例如所有女性 person)的所有 person 时,也会返回 arraylist 实例中引用到的那些 person,如清单 6 所示。
清单 6. 什么是 julia?
@test public void findthegirls() { list<person> girls = db.query(new predicate<person>() { public boolean match(person candidate) { return candidate.getgender().equals(gender.female); } }); boolean maggiefound = false; boolean kaylafound = false; boolean juliafound = false; for (person p : girls) { if (p.getfirstname().equals("maggie")) maggiefound = true; if (p.getfirstname().equals("kayla")) kaylafound = true; if (p.getfirstname().equals("julia")) juliafound = true; }
asserttrue(maggiefound); asserttrue(kaylafound); asserttrue(juliafound); }
注意,对象数据库将尽量地使引用 “correct” — 至少在知道引用的情况下如此。例如,分别在两个不同的查询中检索一个 person(也许是母亲)和检索另一个 person(假设是女儿),仍然认为她们之间存在一个双向关系,如清单 7 所示。
清单 7. 保持关系的真实性
@test public void findjuliaandhermommy() { person maggie = (person) db.get( new person("maggie", "tate", gender.female, 0, null)).next(); person julia = (person) db.get( new person("julia", "tate", gender.female, 0, null)).next();
asserttrue(julia.getmother() == maggie); }
当然,您正是希望对象数据库具有这样的行为。还应注意,如果返回女儿对象的查询的激活深度被设置得足够低,那么对 getmother() 的调用将返回 null,而不是实际的对象。这是因为 person 中的 mother 字段是相对于被检索的原本对象的另一个 “跳跃(hop)”。
更新和删除
至此,您已经看到了 db4o 如何存储和取出多个对象,但是对象数据库如何处理更新和删除呢?就像结构化对象一样,多对象更新或删除期间的很多工作都与管理更新深度有关,或者与级联删除有关。现在您可能已经注意到,结构化对象与集合之间有很多相似之处,所以其中某一种实体的特性也适用于另一种实体。如果将 arraylist 看作 “另一种结构化对象”,而不是一个集合,就很好理解了。
所以,根据到目前为止您学到的东西,我应该可以更新数据库中的某一个女孩。而且,为了更新这个对象,只需将她父母中的一个重新存储到数据库中,如清单 8 所示。
清单 8. 生日快乐,kayla!
@test public void kaylahasabirthday() { person maggie = (person) db.get( new person("maggie", "tate", gender.female, 0, null)).next(); person kayla = (person) db.get( new person("kayla", "tate", gender.female, 0, null)).next();
kayla.setage(kayla.getage() + 1); int kaylasnewage = kayla.getage();
db.set(maggie);
db.close();
db = db4o.openfile("persons.data");
kayla = (person) db.get( new person("kayla", "tate", gender.female, 0, null)).next(); assert(kayla.getage() == kaylasnewage); }
对于多样性关系中的对象,其删除工作非常类似于上一篇文章介绍索的结构化对象的删除工作。只需注意级联删除,因为它对这两种对象可能都有影响。当执行级联删除时,将会从引用对象的每个地方彻底删除对象。如果执行一个级联删除来从数据库中删除一个 person,则那个 person 的母亲和父亲在其 children 集合中突然有一个 null 引用,而不是有效的对象引用。
结束语
在很多方面,将数组和集合存储到对象数据库中并不总与存储常规的结构化对象不同,只是要注意数组不能被直接查询,而集合则可以。不管出于何种目的,这都意味着可以在建模时使用集合和数组,而不必等到持久引擎需要使用集合或数组时才使用它们。
|
|