Skip to content
Advertisement

How to receive not duplicative rows using Room?

I have two related entities:

Station

Connector

When I insert data, I fill up both entites and it seems kinda okay, but when I’m trying to receive stations with particular types of connectors it duplicates rows. For example, I have an object

And if I want to filter stations only by one connector type I receive one row with this station(and it’s right), but if I want to reset filters and look up for stations that can contain many connectors, I receive duplicates of this stations(in this example if I request for station with TYPE_1, TYPE_2 and CHADEMO connector types it will be three equal rows).

I’m using this query to request stations from my database:

I’ve tried to use DISTINCT in the query, ForeignKeys and Indexes in these Entities, but it was not working, so now I’m completely lost.

Advertisement

Answer

If you just want Stations then you have various options then your have various options.

  1. is to use a GROUP BY clause such as GROUP BY simple_stations.id

However, the issue you may then encounter is that Station would be incomplete/unreliable as you have a List of Connectors and if you GROUP by Station then you will only get a single arbitrary Connector (there again that may depend upon you TypeConvertor).

  1. to use DISTINCT you would have to only include the Station columns (similar problem as above).

I’d suggest that your schema is at fault by including the List of Connectors related to the Station you are duplicating data (aka it’s not normalised).

rather if you removed

from the Station Entity the data itself would still be available for retrieval.

You may then wish to have a POJO that Embeds the Station and has a List of Connector’s, perhaps one with and one without the Connector List have an @Relationship (with and you would get all connectors irrespective of the WHERE clause as that’s how @Relationship works). Without and you could have the constructor get only the Connectors with the types you want.

Perhaps consider the following based upon your code:-

The Station Entity

The Connector Entity

The StationWithConnectors POJO NEW

  • note the embedded query to build the list of connectors of only the specfified types

The Dao used i.e. AllDao

The @Database TheDatabase

and finaly an Activity to test/demonstrate

When run in debug mode then:-

StationWithCertainTypes gets both Stations (station 1 has type1 and type2, station2 has type2) as per :-

enter image description here

allswcList has the 2 StationWithConnectors built from the 2 Stations as per :-

enter image description here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement