问题
I'm trying write a query using ORMLite. I need this query check a id of custommer in other entity. How could I do it ?
Entities
@DatabaseTable(tableName = "custommer")
public class Custommer{
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField
private String name;
@DatabaseField
private Sale sale;
//gets sets
}
@DatabaseTable(tableName = "sale")
public class Sale{
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField
private Custommer custommer;
@DatabaseField
private Integer status;
//gets sets
}
Query
Custommer custommer = new Custommer();
custommer.setId(1);
custommer.setName("Fernando Paiva");
QueryBuilder<Sale, Integer> qb = saleDAO.queryBuilder();
Where where = qb.where();
where.eq("sale.custommer.id", custommer.getId());
where.and();
where.eq("sale.status", 1);
PreparedQuery<Sale> pq = qb.prepare();
List<Sale> list = saleDAO.query(pq);
Log.i("SALE LIST->", list.size() + "");
回答1:
You need to use JOIN
Here your example using Join:
- First of all, you need a QueryBuilder to each Dao.
- You can apply your filter to each QueryBuilder separately
- Last but not least, you join the main QueryBuilder (Sales) with the Custommer's QueryBuilder and
- perform the query.
Here the code
Dao<Sale, Integer> saleDao = DaoManager.createDao(getConnectionSource(), Sale.class);
Dao<Custommer, Integer> custommerDao = DaoManager.createDao(getConnectionSource(), Custommer.class);
QueryBuilder<Sale, Integer> saleQa= saleDao.queryBuilder();
saleQa.where().eq("status", 1);
QueryBuilder<Custommer, Integer> custommerQa = custommerDao.queryBuilder();
custommerQa.where().idEq(custommer.getId());
sales = saleQa.join(custommerQa).query();
回答2:
Are you trying to use OrmLite to check if the customer id is the same as the sale id and get all of the matching result? If so the below code will do that
qb.where().eq("id", custommer.id);
List<Sale> results = saleDAO.query(qb.prepare());
Update:
After rereading your question I realized what you're trying to do
qb.where().in(Sale.custommer, id);
See this question for further details. Ormlite Foreign Entity Searching
来源:https://stackoverflow.com/questions/29033931/trying-write-a-query-with-ormlite