Restrict child duplicates on creating object in db4o

半世苍凉 提交于 2019-12-12 04:17:43

问题


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";
    }
}

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?


回答1:


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.



来源:https://stackoverflow.com/questions/7402127/restrict-child-duplicates-on-creating-object-in-db4o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!