OrmLite 执行 sql 语句

OrmLite execute sql statement

我在 OrmLite 中有一个数据库。 这里是 table 之一 — Field:

@DatabaseTable
public class Field {

    @DatabaseField(generatedId = true)
    private long id;

    @DatabaseField
    private String type;

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

我想像这样从 table 中删除一些值:

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

你可以这样做

//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 语句,就像这样

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

But how can I execute this query with DeleteBuilder ?

没有直接的方法可以使用 DeleteBuilder 来执行此操作,因为外来对象实际上在 Field class.

中没有任何信息

但是,这里有一种方法可以使用原始查询然后 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();

但是我需要检查一下以确保。

希望这对您有所帮助。