19

私は Client 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;

そして City Bean 、

@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

これを確実にする1つの方法は、メソッドをオーバーライドし、同時に削除を発行する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 については、以下をお読みください: SQLite を使用した Android の外部キー制約? カスケードの削除について

次に、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 に答える