当使用for循环生成条件时,如何在ormlite中编写查询

时间:2011-09-30 03:44:19

标签: java ormlite

我正在ormlite中编写一个查询,如下所示

Where<Advertisement, Integer> where = queryBuilder.where();
where.and(
    where.between("latitude", pLatitude - APPOXIMATION_FACTOR,
        pLatitude + APPOXIMATION_FACTOR),
    where.between("longitude", pLongitude - APPOXIMATION_FACTOR,
        pLongitude + APPOXIMATION_FACTOR)
      .and().between("width", pWidth - APPOXIMATION_FACTOR,
        pWidth + APPOXIMATION_FACTOR),
);

还有一个和这个

for (int iterator = 0; iterator < moduleList.size(); iterator++) {
    where.eq("id", moduleList.get(iterator).getmId());
    if (iterator != advertisementList.size() - 1){
        whereForModuleID.or();
    }
}

但我在这种情况下如何编写查询

寻求帮助

2 个答案:

答案 0 :(得分:7)

在第二种情况下,我会使用where.in(String, Iterable)方法。你应该这样做:

List<Integer> idList = new ArrayList<Integer>();
for (Module module : moduleList) {
    idList.add(module.getmId());
}
where.in("id", idList);

这变成了一个SQL查询,如:

SELECT * `foo` WHERE `id` IN (7, 17, 1, 34)

以下是where.in()上的文档:

  

http://ormlite.com/docs/where-in

就原始问题而言,请参阅此answer about the where.and(int) and or(int) methods

答案 1 :(得分:0)

要创建按名称和密码查找帐户的查询,请执行以下操作:

 QueryBuilder<Account, String> qb = accountDao.queryBuilder();
 Where where = qb.where();
 // the name field must be equal to "foo"
 where.eq(Account.NAME_FIELD_NAME, "foo");
 // and
 where.and();
 // the password field must be equal to "_secret"
 where.eq(Account.PASSWORD_FIELD_NAME, "_secret");
 PreparedQuery<Account, String> preparedQuery = qb.prepareQuery();

这是我在我的项目中使用的代码,用于使用ORMLite从SQLite获取PropertyModel

public ArrayList<PropertyPicModel> selectArgumentQueryPropertyModel(int property_id, Dao<PropertyPicModel, Integer> dao)
{
    try {
        QueryBuilder<PropertyPicModel, Integer> queryBuilder = dao.queryBuilder();
                Where<PropertyPicModel, Integer> where = queryBuilder.where();
                SelectArg selectArg = new SelectArg();
                // define our query as 'property_id = ?'

                where.eq(ORMLiteConfig.PROPERTY_ID, selectArg);
                // prepare it so it is ready for later query or iterator calls
                PreparedQuery<PropertyPicModel> preparedQuery = queryBuilder.prepare();
                selectArg.setValue(property_id);
                // later we can set the select argument and issue the query

                ArrayList<PropertyPicModel> picList = (ArrayList<PropertyPicModel>) dao.query(preparedQuery);
                return picList;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        MyLog.e("Excep selectArgumentQuery " +e.toString());
    }
    catch (Exception e) {
        MyLog.e("Excep selectArgumentQuery " +e.toString());
    }
    return null;
}

在此示例中,将生成的SQL查询大致为:

 SELECT * FROM account WHERE (name = 'foo' AND passwd = '_secret')

https://github.com/AshishPsaini/ormlite-examples/tree/master/android/HelloAndroid

http://ormlite.com/docs/in