Correct way to handle Bi directional 1:m in Green-DAO

二次信任 提交于 2019-12-10 14:12:35

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/13836417/correct-way-to-handle-bi-directional-1m-in-green-dao

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