2011-07-22 27 views
18

我有一個客戶端Bean,在android上刪除使用ormlite?

@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當所有客戶端刪除一個城市。

請問這是怎麼回事?

回答

52

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

能否請您給的我怎麼會實例CityDao一個例子。例如在我的應用程序中,我有「私人ArtistDao artistDao = null」和「artistDao = new ArtistDao(Artist.class);」。我不知道如何遷移到自定義擴展類,我得到轉換異常,我不知道如何以及在哪裏提供連接源。 –

+0

我不明白@SpeedDemon。你的'ArtistDao'必須是一個具體的類,如果你實例化它。我的文章中的CityDao展示瞭如何擴展'BaseDaoImpl'。 – Gray

+0

我想你的構造函數必須拋出SQLException – Piotr

4

要在Android上使用ORMLite實現級聯您需要啓用外鍵約束如下所述:

(API等級> 16)

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

對於API級別< 16請參閱: 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

相關問題