javakotlinormapache-cayenne

Finding a list of related objects by ID


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.


Solution

  • 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.