限制对db4o中创建对象的孩子重复 [英] Restrict child duplicates on creating object in db4o
问题描述
这是一个很常见的情况,但我使用ORM尤其是在Android的还挺新,所以你的帮助将是真棒。
It's a very common situation, but I'm kinda new using ORM especially in Android, so your help would be awesome.
适用范围:
对象,例如消息有另一个对象的原始字段和字段(子),例如讨论。所以它看起来像:
Scope: Object, e.g. Message has primitive fields and field (child) of another object, e.g. Discussion. So it looks like:
public class Message {
private int id;
private String text;
private Discussion discussion;
public Message(int id, String text, int discussionId){
this.id=id;
this.text=text;
discussion = new Discussion (discussionId);
}
}
public class Discussion {
private int id;
private String title;
public Discussion(int id) {
this.id = id;
this.title = "Sample title";
}
}
的注意::标识是由服务器提供的,这就是为什么它是由手工设置。的
问题:
如你所知多个消息可能属于一个讨论。但是,当我存储信息的名单,我得到表一式两份的讨论(大小相同的消息表)。如何避免呢?
Problem: as you know multiple messages could belong to one discussion. But when I store list of Message I get table with duplicate discussions (the same size as messages table). How to avoid it?
下面我如何保存信息的ArrayList
Here how I store Message ArrayList:
ArrayList<Message> itemsList = new ArrayList<Message>;
itemsList.add(new Message(1, "Message 1", 50));
itemsList.add(new Message(2, "Message 2", 50));
ItemDBProvider dbProvider = new ItemDBProvider();
for (Item item:itemsList) {
dbProvider.store(item);
}
dbProvider.getDB().commit();
dbProvider.close();
我的意思是,不知何故db4o的应该检查一下讨论的对象是已在DB(由ID字段),并限制创建重复。是真的吗?
I mean, somehow db4o should check if Discussion object is already in db (by "id" field) and restrict creating duplicate. Is it real?
推荐答案
db4o的不知道你想要不同的讨论对象合并,只是因为它们具有相同的ID字段。 db4o的通过他们的身份区分对象(即 ==
运营商),而不是对象的任何领域。可以有数百个相等的对象的数据库中的
Db4o does not know that you intend different Discussion objects to be merged, just since they have the same id field. Db4o distinguishes objects by their identity (i.e. the ==
operator), not any fields of the object. You can have hundreds of equal objects in the database.
有没有理由为每个消息一个新的
- 检索现有的,以及设置它作为新的Message对象的讨论
对象讨论
字段。
There is no reason to create a new Discussion
object for each Message
- retrieve the existing one, and set it as the discussion
field of your new Message object.
这篇关于限制对db4o中创建对象的孩子重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!