按 ID 查找相关对象列表
Finding a list of related objects by ID
举例来说,我有一座名为 PersonAnimal
的桥 table。我想搜索所有拥有给定动物 ID 的人。到目前为止的查询如下所示:
Animal animal = getById(Animal.class, animalId)
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL.eq(animal))
.select(context)
但是上面代码段的第一行显示我首先必须从数据库中检索相关对象。我想摆脱那个数据库查找,而是做类似的事情:
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL_ID.eq(animalId)) // <- Find by ID instead
.select(context)
这可能吗?
我是 Apache Cayenne ORM 的 运行 4.1 版。
就在我发布问题时,我找到了答案。您需要使用 Property
对象创建一个 Expression
,如下所示:
val findByIdExpr = Property.create(PersonAnimal.ANIMAL.name, Long::class.java).eq(yourId)
val gotList = ObjectSelect
.query(PersonAnimal.class)
.where(findByIdExpr)
.select(context)
以上代码是 Kotlin 语言,但从 Java 的角度来看也很容易理解。
举例来说,我有一座名为 PersonAnimal
的桥 table。我想搜索所有拥有给定动物 ID 的人。到目前为止的查询如下所示:
Animal animal = getById(Animal.class, animalId)
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL.eq(animal))
.select(context)
但是上面代码段的第一行显示我首先必须从数据库中检索相关对象。我想摆脱那个数据库查找,而是做类似的事情:
ObjectSelect
.query(PersonAnimal.class)
.where(PersonAnimal.ANIMAL_ID.eq(animalId)) // <- Find by ID instead
.select(context)
这可能吗?
我是 Apache Cayenne ORM 的 运行 4.1 版。
就在我发布问题时,我找到了答案。您需要使用 Property
对象创建一个 Expression
,如下所示:
val findByIdExpr = Property.create(PersonAnimal.ANIMAL.name, Long::class.java).eq(yourId)
val gotList = ObjectSelect
.query(PersonAnimal.class)
.where(findByIdExpr)
.select(context)
以上代码是 Kotlin 语言,但从 Java 的角度来看也很容易理解。