2015-09-23 154 views
0

我在OrmLite有一個數據庫。表的 這裏一個 - FieldOrmLite執行sql語句

@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

回答

1

但如何我可以使用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(); 

我需要檢查一下,以確保它。

希望這會有所幫助。

+0

謝謝!它有助於 – winston

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

看起來不是很簡潔) – winston

+0

查看更新的答案。無論如何,你應該形成一個對象集合(或他們的ID)來刪除。 – mohax