Restrict child duplicates on creating object in db4o
Asked Answered
P

1

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?

Pubescent answered 13/9, 2011 at 12:48 Comment(1)
Just a note: db4o is not a ORM (object-relational mapper), it is an object database. No "relational" here.Fionafionna
C
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.

Cleveland answered 13/9, 2011 at 16:9 Comment(4)
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.Pubescent
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.)Fionafionna
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.Pubescent
Hey ! Have the same problem here; did you finally switched to Ormlite ?Isoelectronic

© 2022 - 2024 — McMap. All rights reserved.