Frage

what is the correct way to insert a new object into a Green-DAO DB when dealing with a Bi Directional 1:m relation?

Lets say, I have a chat application that has a conversation entity and a message Entity. every conversation has a list of messages, and every message has a parent conversation.

what I do as of now is:

Conversation conv = new Conversation();
ConversationDao.insert(conv);
List<Message> list = conv.getMessageList();

Message msg = new Message();
MessageDao.insert(msg);

msg.setParent(conv.getId());
list.add(msg);
// SHOULD I UPDATE THE CONVERSATION IN THE DB???

it seems to me like I'm not doing this correctly and I would love to get some guidance ad to the correct way to do this.

thanks in advance...

EDIT:
as can be seen from my comment, after trying to implement code the way I wrote here, I get a null instead of the conversation I was trying to link.
I changed my code a bit and now it looks like this:

private static void linkMessageToAuthorAndParent(Message messageObj, Thread parent) {
    List<Message> threadsMessages = parent.getMessageList();
    messageObj.setThread(parent);

    messageDao.insert(messageObj);

    threadsMessages.add(messageObj);
    Log.d("DtabaseHelper.parseMessage", "message was inserted");
}

but again, my problem is that I'm not sure the connection is now bi-directional.
should I now update the threadsDao?

War es hilfreich?

Lösung

Try it this way:

Conversation conv = new Conversation();
ConversationDao.insert(conv);
List<Message> list = conv.getMessageList();

Message msg = new Message();
msg.setParent(conv.getId()); // Set FK *before* inserting
MessageDao.insert(msg);

list.add(msg);

In the official documentation on relations there is a section "Resolving and Updating To-Many Relations" giving some background info on this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top