2012-02-28 73 views
4

嵌套的對象我有這方面的類:自動刪除ORMLite

public class Station { 
    @DatabaseField(foreign = true, foreignAutoCreate = true) 
    private OpeningTimes openingTimes; 
} 

public class OpeningTimes { 
    @DatabaseField(generatedId = true) 
    int _id; 
} 

現在OpeningTimes行自動創建的,當我呼籲StationDao createOrUpdate方法。那很棒!

我也會很感激,如果我可以自動刪除Station對象及其嵌套對象OpeningTimes。

現在我必須在Station類中這樣做,它似乎很混亂。有沒有更優雅的方式?

public void deleteFromDb(DatabaseHelper dbHelper) { 
    try { 
     openingTimes.deleteFromDb(dbHelper); 
     dbHelper.getStationDao().delete(this); 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

編輯: 我一直也是這個嘗試,但隨着SQL語句錯誤

@DatabaseField(foreign = true, foreignAutoCreate = true, columnDefinition="INTEGER, FOREIGN KEY(`openingTimes_id`) REFERENCES openingtimes(`_id`)") 

回答

8

我會考慮在DAO層面而不是在持久化對象級別這樣做。我建議您創建自己的StationDao界面和您自己的StationDaoImpl實現。該ORMLite文檔和example of this

public interface StationDao extends Dao<Station, Integer> { 
    // we will just be overriding some of the delete methods 
} 

然後創建您的實現這將覆蓋delete()方法並刪除所有子對象。像下面這樣:

public class StationDaoImpl extends BaseDaoImpl<Station, Integer> 
    implements StationDao { 
    private final Dao<OpeningTimes, Integer> openTimesDao; 
    public AccountDaoImpl(ConnectionSource connectionSource) throws SQLException { 
     super(connectionSource, Station.class); 
     openTimesDao = DaoManager.createDao(connectionSource, OpeningTimes.class); 
    } 

    @Override 
    public int delete(Station station) throws SQLException { 
     if (station.openTimes != null) { 
      openTimesDao.delete(station.openTimes); 
     } 
     return super.delete(station); 
    } 
} 

如果您使用的是自己的DAO,那麼你就必須確保它使用@DatabaseTable(daoClass = StationDaoImpl.class)配置。

+2

這仍然可以使用'PreparedDelete'嗎?因爲我想用'DELETE ID NOT IN'來完成與遠程數據庫的完全同步。 – dzeikei 2014-03-06 23:23:51