Restrict child duplicates on creating object in db4o
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 D开发者_开发技巧iscussion 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";
}
}
note :: id is provided by server, that's why it's set by hand.
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?
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();
I mean, somehow db4o should check if Discussion object is already in db (by "id" field) and restrict creating duplicate. Is it real?
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.
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.
精彩评论