Trying write a query with ORMLite?

2019-08-03 04:14发布

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

2条回答
在下西门庆
2楼-- · 2019-08-03 04:50

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

查看更多
我只想做你的唯一
3楼-- · 2019-08-03 05:02

You need to use JOIN

Here your example using Join:

  1. First of all, you need a QueryBuilder to each Dao.
  2. You can apply your filter to each QueryBuilder separately
  3. Last but not least, you join the main QueryBuilder (Sales) with the Custommer's QueryBuilder and
  4. 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();
查看更多
登录 后发表回答