简体   繁体   中英

How to delete a List of Objects/Entities from room database?

I had an idea on how to delete a single entity or delete all entities from the Room database. But I want to delete a List of Entities from the room database but haven't found any solution.

I had tried these codes but not working.

@Delete(entity = CollectionData.class)
void deleteList(List<CollectionData> collectionDataList);

and

@Delete
void deleteList(List<CollectionData> collectionDataList);

none of these codes working. Any help...

What you have written above should work. can you answer below questions?

  1. is CollectionData annotated with @Entity?
  2. have you defined any primary key for entity class?
  3. when you are calling this delete method, make sure that the object that you are passing has that primary key.

can you also post your entity class?

As a workaround you can also do something like this:

@Query("delete from tableName where id in (:idList)")
fun deleteDataById(idList: List<Int>) 

You Dao is fine, so it is probably your list that is incorrect. One trap that people tend to fall into is using the objects that have not had the primary key assigned with the value assigned when that primary key is generated when inserted.

@PrimaryKey(autogenerate = true)
long the_variable_aka_columnname;
....
  • long can be Long, int, Integer

A variation that is similar is

@PrimaryKey
Long the_variable_aka_columnname = null;
  • Long or Integer

Both result in the column being INTEGER PRIMARY KEY NOT NULL (the former has AUTOINCREMENT) which makes the column an alias of the rowid and thus Room will supply no value and the result is that the value will be assigned.

So the object used to insert is NOT the same as the resultant column and thus, if used for the delete, will not result in the row(s) being deleted.

I suspect that this might well be cause or somehow you have not extracted the @Primary Key Value.

Demonstration

The @Entity CollectionData :-

@Entity
class CollectionData {
    @PrimaryKey
    Long id = null;
    String name;

    CollectionData(){}

    @Ignore
    CollectionData(String name) {
        this.name = name;
    }
}
  • the id column if not specifically set will be given a value, similar to having autogenerate = true

An @Dao class CollectionDataDao :-

@Dao
abstract class CollectionDataDao {
    @Insert
    abstract long[] insert(ArrayList<CollectionData> collectionDataArrayList);
    @Delete
    abstract int delete(List<CollectionData> collectionDataList);
    @Query("SELECT * FROM collectiondata WHERE name LIKE :preWildChar||:nameSelection||:postWildChar")
    abstract List<CollectionData> getByName(String preWildChar, String nameSelection, String postWildChar);
    @Query("DELETE FROM collectiondata")
    abstract int deleteAll();
}

A pretty standard @Database class so no need to include (note for convenience and brevity .allowManThreadQueries has been used).

And some code in an activity, that gets the database and the dao and then :-

  • deletes any existing data (for easy rerun ability)
  • creates an ArrayList of CollectionData's (4)
  • inserts them (obtaining the list of id's)
  • writes out the list of id's
  • writes out the Arraylist ie id's are all null
  • deletes according to the ArrayList writing out the number of deletions
    • 0 as there are no rows with an id of null
  • deletes according to a list that is obtained from the database (with the respective id's), writing out the number deleted
    • 2 DELETED as the ids match what is in the database
  • modifies the original ArrayList changing the name to what is not stored and changing the id to the respective id via the id's inserted.
  • deletes according to the altered original list and writes out the number deleted.
    • the remaining 2 . That is 2 of the 4 inserted were deleted above so 2 match.
    • changing the name shows that the important value is the id (the primary key) that is only the primary key is used to determine what is deleted.
    • in essence Room builds the SQL DELETE FROM the_table WHERE the_primary_key IN (the_list_of_primary_key_values_from_the_list_of_objects);

The code is :-

    db = TheDatabase.getInstance(this);
    daoCollectionData = db.getCollectionDataDao();
    daoCollectionData.deleteAll();
    ArrayList<CollectionData> cdl = new ArrayList();
    cdl.add(new CollectionData("CD001"));
    cdl.add(new CollectionData("CD002"));
    cdl.add(new CollectionData("CD003"));
    cdl.add(new CollectionData("CD0030"));
    /* Insert the Collection Datas  getting the IDs*/
    long[] insertedIdList = daoCollectionData.insert(cdl);
    /* Show the IDs (write to the log) */
    for(long l: insertedIdList) {
        Log.d("CDINFO","Insert ID = " + l);
    }
    /* The the original Collection Datas (null ID's) */
    for(CollectionData cd: cdl) {
        Log.d("CDINFO","Name = " + cd.name + " ID = " + cd.id);
    }
    /* DELETE according to original list. Note will not delete because IDs have not been set don't match */
    Log.d("CDINFO","CollectionData's deleted = " + daoCollectionData.delete(cdl));
    /* Extract some and delete (any with a 3 in the name)*/
    List<CollectionData> deleteList = daoCollectionData.getByName("%","3","%");
    Log.d("CDINFO"," CollectionData's deleted = " + daoCollectionData.delete(deleteList));
    /* alter the cdl list to set the ids */
    for (int i=0; i < insertedIdList.length; i++) {
        CollectionData replace = cdl.get(i);
        replace.id = insertedIdList[i];
        replace.name = "not the original name";
        cdl.set(i,replace);
    }
    /* Show the altered original list */
    for(CollectionData cd: cdl) {
        Log.d("CDINFO","Name = " + cd.name + " ID = " + cd.id);
    }
    /* and delete them */
    Log.d("CDINFO","CollectionData's deleted = " + daoCollectionData.delete(cdl));

The output to the Log is :-

2021-10-18 22:37:18.295 D/CDINFO: Insert ID = 1
2021-10-18 22:37:18.295 D/CDINFO: Insert ID = 2
2021-10-18 22:37:18.295 D/CDINFO: Insert ID = 3
2021-10-18 22:37:18.295 D/CDINFO: Insert ID = 4
2021-10-18 22:37:18.295 D/CDINFO: Name = CD001 ID = null
2021-10-18 22:37:18.295 D/CDINFO: Name = CD002 ID = null
2021-10-18 22:37:18.295 D/CDINFO: Name = CD003 ID = null
2021-10-18 22:37:18.295 D/CDINFO: Name = CD0030 ID = null
2021-10-18 22:37:18.303 D/CDINFO: CollectionData's deleted = 0
2021-10-18 22:37:18.308 D/CDINFO:  CollectionData's deleted = 2
2021-10-18 22:37:18.308 D/CDINFO: Name = not the original name ID = 1
2021-10-18 22:37:18.308 D/CDINFO: Name = not the original name ID = 2
2021-10-18 22:37:18.308 D/CDINFO: Name = not the original name ID = 3
2021-10-18 22:37:18.308 D/CDINFO: Name = not the original name ID = 4
2021-10-18 22:37:18.311 D/CDINFO: CollectionData's deleted = 2
  • You may wish to adapt the code to write your data to the log which may help to pinpoint what is wrong with the list you pass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM