如何在使用room关系时通过查询访问子实体的列?

fdbelqdn  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(196)

我有两个实体订单和客户。每个订单与零个或单个客户关联,每个客户与零个或多个订单关联。

@Entity
public class Order {
    @PrimaryKey(autoGenerate = true)
    public long id;
    public long customerId;
    ....
}

@Entity
public class Customer {
    @PrimaryKey(autoGenerate = true)
    public long id;
    public String name;
}

我想用对应的客户查询order表,如果它存在的话。
因此,我创建了文档后面的关系。

public class OrderAndCustomer {
    @Embedded public Order order;
    @Relation(
            parentColumn = "customerId",
            entityColumn = "id"
    )
    public Customer customer;
}

我可以使用dao查询订单列表和相应的客户。

@Dao
public interface OrderDao {
    @Transaction
    @Query("select * from `order`")
    List<OrderAndCustomer> getOrderAndCustomer();
}

但是当我试图访问子实体的列时,我得到了编译错误。例如,我想查询客户名称类似****的订单。
因此,我更新的查询:

@Query("select * from `order` where customer.name like '****'")

是否可以访问where子句中子实体的属性?
所以,问题来了,这种关系是如何运作的!?我发现它首先查询订单实体,然后查询客户实体。如果我错了,让我指出正确的方法。
我有另一个解决方案来查询多个表,但我无法使用房间提供的关系功能,或者我遗漏了一些东西!
我可以按照这个答案使用连接和Map到对象。

public class OrderAndCustomer extends Order {
    public String customerName;
}

查询:

@Query("select `order`.*, customer.name as customerName from `order` left outer join customer on `order`.customerId = customer.id where customerName like '****'")
List<OrderAndCustomer> getOrderAndCustomer();

但是,仍然有疑问。如何Maporder和customer表的所有列?我是否需要将客户的所有列与 as 在查询中还是有另一种简化的方法可用?如果两个表都有更多的列,并且我需要提取第一个表和第二个表的所有列,那么我的查询就足够长了。我想知道是否有最简单的方法来Map两个表而不使用或最少使用 as 包含第二个表的所有列。
帮助我找到正确的方法和更好的解决方案。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题