Deleting using ormlite on android?

老子叫甜甜 提交于 2019-12-03 01:34:17
Gray

ORMLite does not support cascading deletes @Majid. That is currently outside of what it considers to be "lite". If you delete the city then you need to delete the clients by hand.

One way to ensure this would be to have a CityDao class that overrides the delete() method and issues the delete through the ClientDao at the same time. Something like:

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);
    }
    ...
}
Benjamin Carroll

To implement cascading while using ORMLite on Android you need to enable foreign key restraints as described here:

(API level > 16)

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

For API level < 16 please read: Foreign key constraints in Android using SQLite? on Delete cascade

Then use columnDefinition annotation to define cascading deletes. Ex:

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

This is assuming the table/object name is "my_table", as described here: Creating foreign key constraints in ORMLite under SQLite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!