【问题标题】:Deleting using ormlite on android?在android上使用ormlite删除?
【发布时间】:2011-10-10 23:18:10
【问题描述】:

我有一个客户端 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 的客户端。

请问这怎么可能?

【问题讨论】:

    标签: android ormlite foreign-collection


    【解决方案1】:

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

    【讨论】:

    • 您能否举个例子说明我将如何实例化 CityDao。例如,在我的应用程序中,我有“private ArtistDao artistDao = null”和“artistDao = new ArtistDao(Artist.class);”。我不知道如何迁移到自定义扩展类,我得到强制转换异常,我不知道如何以及在哪里提供连接源。
    • 我不明白@SpeedDemon。如果您实例化它,您的 ArtistDao 必须是一个具体的类。我帖子中的CityDao 展示了如何扩展BaseDaoImpl
    • 我猜你的构造函数必须抛出 SQLException
    【解决方案2】:

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

    (API 级别 > 16)

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

    对于 API 级别 Foreign key constraints in Android using SQLite? on Delete cascade

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

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

    假设表/对象名称为“my_table”,如下所述:Creating foreign key constraints in ORMLite under SQLite

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多