Finding a list of related objects by ID

与世无争的帅哥 提交于 2020-01-06 11:10:44

问题


Let's say for example I have a bridge table called PersonAnimal. I want to search for all the people who have a given animal's ID. The query so far looks like:

Animal animal = getById(Animal.class, animalId)
ObjectSelect
    .query(PersonAnimal.class)
    .where(PersonAnimal.ANIMAL.eq(animal))
    .select(context)

However the first line in the above code segment shows that I first have to retrieve the related object from the database. I want to get rid of that database lookup and instead do something like:

ObjectSelect
    .query(PersonAnimal.class)
    .where(PersonAnimal.ANIMAL_ID.eq(animalId)) // <- Find by ID instead
    .select(context)

Is that possible?

I am running version 4.1 of the Apache Cayenne ORM.


回答1:


Just as I posted the question I found the answer. You need to create an Expression using a Property object like so:

val findByIdExpr = Property.create(PersonAnimal.ANIMAL.name, Long::class.java).eq(yourId)
val gotList = ObjectSelect
   .query(PersonAnimal.class)
   .where(findByIdExpr)
   .select(context)

Above code is in Kotlin but is also easy to understand from a Java perspective.



来源:https://stackoverflow.com/questions/53563264/finding-a-list-of-related-objects-by-id

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