Realm Java关联模型查询:如何按Technician ID查询Shipment
正确的Realm关联查询方式:匹配指定Technician ID的Shipment数据
嘿,我懂你现在的困扰——你想用Realm查询关联了特定Technician ID的Shipment数据,但之前用的contains方法完全不对路子,因为contains是用来匹配字符串内容的,而这里我们要针对关联对象的字段做精准匹配。
为什么你的原有代码行不通?
你的Shipment类里的technician是一个RealmObject关联对象,不是字符串类型。用contains("technician", "11")本质上是在尝试把Technician对象转换成字符串后匹配内容,这显然不是你想要的效果,自然查不到正确的数据。
正确的查询方法
Realm支持通过点语法直接访问关联对象的字段,我们可以用equalTo方法来精准匹配Technician的id字段,这里有两种常用的实现方式:
方式1:直接通过Technician ID查询
如果只有Technician的ID,直接用点路径关联查询即可:
public RealmResults<Shipment> forTechnician(int technicianId) { Realm realm = Realm.getDefaultInstance(); try { // 用点语法访问关联对象的id字段 return realm.where(Shipment.class) .equalTo("technician.id", technicianId) .findAll(); } finally { // 务必关闭Realm实例,避免资源泄漏 realm.close(); } }
方式2:通过已有的Technician对象查询
如果你已经持有了目标Technician的Realm对象实例,也可以直接匹配整个对象:
public RealmResults<Shipment> forTechnician(Technician technician) { Realm realm = Realm.getDefaultInstance(); try { return realm.where(Shipment.class) .equalTo("technician", technician) .findAll(); } finally { realm.close(); } }
额外提醒
- 一定要注意Realm实例的生命周期管理,用
try-finally确保关闭实例,否则会造成内存泄漏。如果你的Realm版本支持(Realm 5.0+),也可以用Java的try-with-resources语法简化:try (Realm realm = Realm.getDefaultInstance()) { return realm.where(Shipment.class) .equalTo("technician.id", technicianId) .findAll(); } findAll()返回的RealmResults是实时更新的数据集,如果不需要实时更新,可以调用findAllAsync()或者copyFromRealm()获取离线副本。
内容的提问来源于stack exchange,提问作者Lewis Smith
相关产品推荐
相关产品推荐

