0

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?

Oleksii Malovanyi
  • 6,780
  • 6
  • 24
  • 27

1 Answers1

3

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.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • Many thanks for your explanations. Maybe, I should find another way to store objects in db, cause this check-before-save sounds like a pain. – Oleksii Malovanyi Sep 13 '11 at 20:55
  • Not "check before save", but "check before create". Simply don't have any duplicate Discussion objects. (Or don't have them part of the Message, only store the discussion ID. But then you'll have to look them up when you need them.) – Paŭlo Ebermann Sep 13 '11 at 20:58
  • Yeap, discussion ID could deal with situation, but as a lazy boy I hoped for needless writing extra code for "getting field objects on demand". Heh, thanks again! Maybe I'll give ormlite a try and see how it handles "foreign" relations for field objects. – Oleksii Malovanyi Sep 13 '11 at 21:29
  • Hey ! Have the same problem here; did you finally switched to Ormlite ? – bashizip Mar 26 '14 at 10:12