19

我有一个客户端 bean,

@DatabaseField(columnName = "client_id",generatedId = true,useGetSet = true)
private Integer clientId;
@DatabaseField(columnName = "client_nom",useGetSet = true)
private String clientNom;
@DatabaseField(columnName = "city_id",foreign = true,useGetSet = true)
private City city;

和一个城市豆,

@DatabaseField(columnName = "city_id",generatedId = true,useGetSet = true)
private Integer cityId;
@DatabaseField(columnName = "city_name",useGetSet = true)
private String cityName;
@ForeignCollectionField
private ForeignCollection<Client> clientList;

这些 bean 只是一个示例,但假设我想在删除城市时删除所有具有外国城市 cityId 的客户端。

请问这怎么可能?

4

2 回答 2

51

ORMLite不支持级联删除@Majid。这目前超出了它认为的“精简”范围。如果删除,city则需要clients手动删除。

确保这一点的一种方法是拥有一个CityDao覆盖该delete()方法并同时发出删除的类ClientDao。就像是:

public class CityDao extends BaseDaoImpl<City, Integer> {
    private ClientDao clientDao;
    public CityDao(ConnectionSource cs, ClientDao clientDao) {
        super(cs, City.class);
        this.clientDao = clientDao;
    }
    ...
    @Override
    public int delete(City city) {
        // first delete the clients that match the city's id
        DeleteBuilder db = clientDao.deleteBuilder();
        db.where().eq("city_id", city.getId());
        clientDao.delete(db.prepare());
        // then call the super to delete the city
        return super.delete(city);
    }
    ...
}
于 2011-07-22T13:34:55.407 回答
4

要在 Android 上使用 ORMLite 时实现级联,您需要启用外键限制,如下所述:

(API 级别 > 16)

@Override
public void onOpen(SQLiteDatabase db){
    super.onOpen(db);
    if (!db.isReadOnly()){
        db.setForeignKeyConstraintsEnabled(true);
    }
}

对于 API 级别 < 16,请阅读: Android 中使用 SQLite 的外键约束?在删除级联

然后使用 columnDefinition 注解来定义级联删除。前任:

@DatabaseField(foreign = true,
columnDefinition = "integer references my_table(id) on delete cascade")
private MyTable table;

这是假设表/对象名称是“my_table”,如下所述:在 SQLite 下的 ORMLite 中创建外键约束

于 2014-10-29T16:55:56.743 回答