Finding a list of related objects by ID

2019-08-20 01:50发布

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条回答
何必那么认真
2楼-- · 2019-08-20 02:01

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.

查看更多
登录 后发表回答