Alex Voronsky
Alex Voronsky

Reputation: 106

Joining a query by using Room

I have two Room entities:

@Entity(tableName = LocationsTable.NAME)
data class LocationDto(@PrimaryKey val timestamp: Long,
                   val latitude: Double,
                   val longitude: Double,
                   val altitude: Double)

@Entity(tableName = TripsTable.NAME)
data class TripDto(@PrimaryKey(autoGenerate = true) val _id: Long,
               val startTime: Long,
               val endTime: Long)

And now I'm trying to do a JOIN to get an object like this:

data class TripWithLocationDto(val startTime: Long,
                        val endTime: Long,
                        val locations: List<LocationDto>)

Locations must contain locationDtos between start and end times of a trip entity. The query should look similar to:

SELECT trips_table.start_time, trips_table.end_time FROM trips_table JOIN locations_table WHERE locations_table.timestamp >= trips_table.start_time AND locations_table.timestamp <= trips_table.end_time

All articles describe the implementation with foreign keys only. Who knows how to make it work?

Upvotes: 4

Views: 5986

Answers (1)

tushar
tushar

Reputation: 56

You create foreign keys in the entity class which you want to join, and after that make another entity class in which you take field of both tables you are joining and put join query as you made above in dao. You can check below link also. in many to many relationship tag

https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a

You can also visit below link which is in kotlin:-

http://danielgaribaldi.com/room-persistence-library-part-2-room-relationships/

Upvotes: 1

Related Questions