I have two entity order and customer. Each order is associated with zero or single customer and each customer is associated with zero or many orders.
@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;
}
I wanted to query the order table with the corresponding customer if it exists.
So, I have created the relation following the documentation.
public class OrderAndCustomer {
@Embedded public Order order;
@Relation(
parentColumn = "customerId",
entityColumn = "id"
)
public Customer customer;
}
I can query the list of orders and the corresponding customer using dao.
@Dao
public interface OrderDao {
@Transaction
@Query("select * from `order`")
List<OrderAndCustomer> getOrderAndCustomer();
}
But when I try to access the columns of child entity, I got compile error. For instance, I wanted to query the order where customer name is like ****.
Therefore, my updated query:
@Query("select * from `order` where customer.name like '****'")
Is it possible to access the attribute of child entity in where clause?
So, the question arises that how the relation works!? I have figure out that it first query the order entity and then query the customer entity. Let me show the correct way If I am wrong.
I have another solution to query multiple tables but I am unable to use the relation feature what room provides or I am missing something!
I can follow this answer to use join and mapping to object.
public class OrderAndCustomer extends Order {
public String customerName;
}
Query:
@Query("select `order`.*, customer.name as customerName from `order` left outer join customer on `order`.customerId = customer.id where customerName like '****'")
List<OrderAndCustomer> getOrderAndCustomer();
But, Still have questions.
How do I map all columns of the order and customer table? Do I need to map all columns of customer with as
in the query or there is another simplified approach available? If both tables has more columns and I need all of the columns of the first and second table to be fetched, then my query will be long enough. I wonder if there is the simplest thing to map both tables without or minimal using of as
with all columns of the second table.
Help me with the right approach and better available solution.