javakotlinormapache-cayenne

Finding a list of objects by Primary Key ID - Apache Cayenne


This is kind of related to my previous question where I discussed finding rows by foreign key IDs. This question is directed at finding a list of objects by primary key ID.

In the below code I am trying to find a list of Person objects by providing a list of ids. But Apache Cayenne cannot do that because ID_PK_COLUMN is a string and not a Property.

ObjectSelect
    .query(Person::class.java)
    .where(Person.ID_PK_COLUMN.in(listOfIds)) // <- Cannot perform this
    .select(context)

How can I find a list of Person objects by ID?

I know we have Cayenne.objectForPK but that only finds one object.

Using Apache Cayenne 4.1.


Solution

  • Since ids are generally not mapped as object properties in Cayenne and "ID_PK_COLUMN" is a "db:" property, you need to build a "db" expression for the "where" method argument. There's an API for that:

    ExpressionFactory.inDbExp(Person.ID_PK_COLUMN, listOfIds)
    

    (BTW, Property is just syntactic sugar on top of ExpressionFactory)