How to make many-to-many relation query in GreenDAO with source property other than primary key?

241 Views Asked by At

Let's assume we have following entities: Item:

class Item {
...
    @Index(unique=true)
    private String guid;
...
    @ToMany
    @JoinEntity(entity = JoinItemsWithTags.class, sourceProperty = "itemGuid", targetProperty = "tagName")
    private List<Tag> tagsWithThisItem;
    ...
}

Tag:

class Tag {
    @Id
    private Long localId;
    @Index(unique = true)
    private String name;
    ...
}

and we need to join them. Here is my join entity class:

@Entity(nameInDb = "item_tag_relations")
class JoinItemsWithTags {
    @Id
    private Long id;
    private String itemGuid;
    private String tagName;
    ...
}

I want to use tag name as a join property instead of Long id, because it's easier to support consistency when syncing with server. But currently tags getter in Item class always return an empty list. I've looked into log and found generated query which using internally in that getter:

SELECT * <<-- there were a long sequence of fields
FROM "tags" T  JOIN item_tag_relations J1 
ON T."_id"=J1."TAG_NAME" <<-- here is the problem, must be `T."NAME"=J1."TAG_NAME"` 
WHERE J1."ITEM_GUID"=?

So the problem is that join is base on tag's _id field. Generated List<Tag> _queryItem_TagsWithThisItem(String itemGuid) method implicitly uses that id to make a join:

// this `join` nethod is overloaded and pass tag's id as source property
queryBuilder.join(JoinItemsWithTags.class, JoinItemsWithTagsDao.Properties.TagName)
                    .where(JoinItemsWithTagsDao.Properties.ItemGuid.eq(itemGuid));

Correct approach is this case might be following, I suppose:

// source property is passed explicitly
queryBuilder.join(/* Desired first parameter -->> */ TagDao.Properties.Name,
    JoinItemsWithTags.class, JoinItemsWithTagsDao.Properties.TagName)
                    .where(JoinItemsWithTagsDao.Properties.ItemGuid.eq(itemGuid));

But this code is in generated dao, and I don't know how to do anything with it. Is there any way to workaround this?

0

There are 0 best solutions below