2

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

@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;
}

我想查询对应客户的订单表是否存在。

所以,我按照文档创建了关系。

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 子句中访问子实体的属性?

那么问题来了,这种关系是如何运作的!?我发现它首先查询订单实体,然后查询客户实体。如果我错了,让我展示正确的方法。

我有另一种查询多个表的解决方案,但我无法使用房间提供的关系功能,或者我遗漏了一些东西!

我可以按照这个答案使用连接和映射到对象。

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();

但是,仍有疑问。如何映射订单和客户表的所有列?我是否需要as在查询中映射所有客户列,或者有另一种简化的方法可用?如果两个表都有更多列并且我需要获取第一个和第二个表的所有列,那么我的查询将足够长。我想知道是否有最简单的方法来映射两个表而不使用或最少使用as第二个表的所有列。

帮助我采用正确的方法和更好的可用解决方案。

4

0 回答 0