OrmLite执行sql语句

时间:2015-09-23 09:51:03

标签: android sqlite ormlite

我在OrmLite有一个数据库。 其中一个表格为Field

@DatabaseTable
public class Field {

    @DatabaseField(generatedId = true)
    private long id;

    @DatabaseField
    private String type;

    @ForeignCollectionField(eager = true)
    private Collection<FieldListValue> listValue;
    ...
}

我想以这种方式从表中删除一些值:

List<Field> fields = fieldDao.queryForAll();
for (Field field : fields) {
    if (field.getType().equals("list") && field.getListValue().size() == 0) {
        fieldDao.delete(field);
    }
}

但是如何使用DeleteBuilder执行此查询?

这段代码的问题...(SELECT COUNT(listValue) FROM Field) = 0

2 个答案:

答案 0 :(得分:2)

  

但是如何使用DeleteBuilder执行此查询?

没有直接的方法可以使用DeleteBuilder来执行此操作,因为外部对象实际上没有Field类中的信息。

但是,这是使用原始查询然后DeleteBuilder完成此操作的一种方法。

近似代码:

qb = fieldListValueDao.queryBuilder();
// raw query for the field_ids in the fieldListValue table
rawResults = qb.queryRaw("SELECT field_id FROM fieldListValue GROUP BY field_id",
    new RawRowMapper<Integer>() {
        // each result row is a single integer in the 0th column
        public Integer mapRow(String[] columnNames, String[] resultColumns) {
            return Integer.parseInt(resultColumns[0]);
        }
    });

有关原始查询的帮助,请参阅:http://ormlite.com/docs/raw-queries

获得field_id值的原始结果后,您可以执行以下操作:

deleteBuilder = fieldDao.deleteBuilder();
// delete any rows that are not in the raw-results -- who have no fieldListValue entries
deleteBuilder.where().notIn("id", rawResults);
deleteBuilder.delete();

您也可以使用notIn("id", queryBuilder)方法:

qb = fieldListValueDao.queryBuilder();
qb.selectColumns("field_id");
qb.groupBy("field_id");
...
deleteBuilder = fieldDao.deleteBuilder();
deleteBuilder.where().notIn("id", qb);
deleteBuilder.delete();

我需要检查一下以确保这一点。

希望这有帮助。

答案 1 :(得分:0)

你可以这样做

//get instance of DeleteBuilder
DeleteBuilder<Field, Integer> deleteBuilder = fieldDao.deleteBuilder();
//construct yours WHERE
//in this exampe we select fields with "id"=0
deleteBuilder.where().eq("id", 0);
//call delete
deleteBuilder.delete();

如果你想在你的代码条件之后删除所需的行,你可以形成一个要删除的对象的ArrayList,然后将它们的id传递给deleteBuilder where where statement

List<Integer> ids= new ArrayList<Integer>();
List<Field> fields = fieldDao.queryForAll();
List<Field> fieldsToDelete = new ArrayList<Field>();
for (Field field : fields) 
{
    if (field.getType().equals("list") && field.getListValue().size() == 0)
    {
        ids.add(field.getId);
        fieldsToDelete.add(field);
    }
}
fieldDao.delete(ids);
//or
fieldDao.delete(fieldsToDelete);
//or
//get instance of DeleteBuilder
DeleteBuilder<Field, Integer> deleteBuilder = fieldDao.deleteBuilder();
//construct yours WHERE
//in this exampe we select fields with "id"=0
deleteBuilder.where().in("id", ids);
//call delete
deleteBuilder.delete();