我想在我的项目中实现 android ROOM 。 但我无法解决Order(customer_id)和Customer(id)之间的一对一关系。
是否可以在OrderDao界面中填写客户(@Ignore protected Customer customer)字段?
我只能解决java代码。还有其他方法吗?
// Customer.java
@Entity (tableName = "t_customer")
public class Customer {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
protected String mId;
@ColumnInfo(name = "name")
protected String mName;
}
// Order.java
@Entity(tableName = "t_order",
foreignKeys = {
@ForeignKey(entity = Customer.class,
parentColumns = "id",
childColumns = "customer_id",
onDelete = SET_NULL) }
public class Order {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
protected String mId;
@ColumnInfo(name = "description")
protected String mDescription;
@ColumnInfo(name = "customer_id")
protected String mCustomerId;
@Ignore
**protected Customer customer;**
//....
}
//OrderDao.java
@Dao
public interface OrderDao {
@Query("SELECT * from t_order ORDER BY id DESC")
LiveData<List<Order>> listByIds();
@Query("SELECT * from t_order WHERE id = :id LIMIT 1")
LiveData<Order> readById(long id);
//....
}
答案 0 :(得分:2)
截至目前,无法自动填充Customer
。您需要创建另一个名为OrderWithCustomer
的POJO,可能看起来如下所示:
public class OrderWithCustomer {
@Embedded
private Order order;
@ColumnInfo(name = "name")
private String customerName;
}
在您的DAO
:
@Dao
interface OrderDao {
@Query("SELECT t_order.* name FROM t_order LEFT JOIN t_customer ON t_order.customer_id = t_customer.id")
public List<OrderWithCustomer> getOrderWithCustomer();
}