createOrUpdate() always creates a new entry in the database with ORMLite

前端 未结 3 1054
星月不相逢
星月不相逢 2020-12-31 08:19

In my Android project, ORMLite is functioning as a cache. I\'m downloading data from a web server and placing it in the database. I\'m calling createOrUpdate on

相关标签:
3条回答
  • 2020-12-31 08:39

    You should not be calling createOrUpdate unless your object already has an id field set. The way ORMLite determines whether or not it exists in the database is to do a query-by-id on it. The code does:

    ID id = extractId(data);
    // assume we need to create it if there is no id  <<<<<<<<<<<<<<<<<<<<<<<
    if (id == null || !idExists(id)) {
        int numRows = create(data);
        return new CreateOrUpdateStatus(true, false, numRows);
    } else {
        int numRows = update(data);
        return new CreateOrUpdateStatus(false, true, numRows);
    }
    

    I'll expand the javadocs to explain this better. They are very weak there. Sorry. I've updated them to be:

    This is a convenience method for creating an item in the database if it does not exist. The id is extracted from the data argument and a query-by-id is made on the database. If a row in the database with the same id exists then all of the columns in the database will be updated from the fields in the data parameter. If the id is null (or 0 or some other default value) or doesn't exist in the database then the object will be created in the database. This also means that your data item must have an id field defined.

    0 讨论(0)
  • 2020-12-31 08:57

    set your primary key for it to work normally.

    @DatabaseField(columnName = "id",uniqueIndex = true) private int id;

    Worked for me. Exceptions are thrown at background but it works :D

    0 讨论(0)
  • 2020-12-31 08:58

    It seems like you manually need to extract the id of the already existing entry and then update the database, based on your actual unique identifier. Example with unique URLs:

    CacheItem newEntry = fetchEntry("..."); // fetch it here
    List<CacheItem> existing = mDao.queryForEq("url", newEntry.getUrl());
    if (existing.size() > 0) {
        int id = existing.get(0).getId();
        newEntry.setId(id);
        mDao.update(newEntry);
    } else mDao.create(newEntry);
    
    0 讨论(0)
提交回复
热议问题