如何在 android 中使用 Room Persistence Library 查询嵌套的嵌入式对象?

How to query nested Embeded objects using Room Persistance Library in android?

假设我有 3 个 类 用户、地址、位置

class Address {
    public String street;
    public String state;
    public String city;

    @ColumnInfo(name = "post_code")
    public int postCode;

    @Embedded(prefix = "home_")
    public Location homeLocation;

    @Embedded(prefix = "office_")
    public Location officeLocation;
}

class Location{
     public long lat;
     public long lng;
}

@Entity
class User {
    @PrimaryKey
    public int id;

    public String firstName;

    @Embedded(prefix = "addr_")
    public Address address;
}

我应该如何编写查询以获取家庭位置在特定纬度和经度边界之间的用户?

例如:如果我想找到其家庭位置在这两点 Location1(13.135795,77.360348) & Location2(12.743639, 77.901424) 之间的所有用户。 我的查询看起来像这样 -

select * from User where address.homelocation.lat < :l1_latitude && address.homelocation.lat > l2_latitude && address.homelocation.lng > :l1_longitude && address.homelocation.lng < :l2_longitude

如果我必须根据我的理解在嵌入位置使用前缀,如果错误请纠正我,地址中的所有字段都将附加前缀。所以我可以将城市查询为 addr_city,如果我必须在 homeLocation 内查询纬度,那么它会变成 addr_home_lat 吗?

房间数据库中允许嵌套嵌入对象吗?如果是,那么我如何查询嵌套的嵌入对象?

这里需要一些帮助。谢谢你。

是 "nested embedded objects" 允许进入 ROOM。您可以编写一个具有嵌入式地址 class 的用户 class,因为它包含一个嵌入式位置 class.

每次添加嵌入对象时,空间都会使 table 变平。在您的案例中,room 生成一个名为 "User" 的 table,其中包含以下列:

id, firstName, addr_street, addr_state, addr_city, addr_post_code, addr_home_lat, addr_home_lng, addr_office_lat , addr_office_lng

所以你的查询应该是这样的:

@Query("SELECT * FROM User WHERE " +
        "addr_home_lat BETWEEN :lat1 AND :lat2" +
        " AND addr_home_lng BETWEEN :lng1 AND :lng2")
List<User> findInRange(long lat1, long lat2, long lng1, long lng2);

请注意,"lat" 已展平为 "addr_home_lat","lng" 展平为 "addr_home_lng"。因此,您可以使用这些列名来应用过滤器逻辑。

如果您拼错了列名,例如 "home_lng" 而不是 "addr_home_lng",那么 room 会发现并报错:

There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: home_lng)

有关房间数据库的更多信息,请查看 Google I/O 演讲。