Tuesday, 28 August 2018

Polymorphic entities in Room

Here's the sample query:

    @Query("SELECT * FROM PhotosMediaItem WHERE PhotosMediaItem = :albumId " +
        "UNION SELECT * FROM VideosMediaItem WHERE VideosMediaItem = :albumId" +
        " ORDER by CreationDate DESC")
    List<MediaItem> getAllMediaInAlbum(int albumId);

There are 3 entities in my Room DB:

Album, PhotosMediaItem and VideosMediaItem.

VideosMediaItem and PhotosMediaItem inherit from MediaItem.

MediaItem is not an entity in the DB, it's just an abstract base class.

I would like to create a query that returns all the photos and videos media items in a specific album with descending order based on their creation date.

So the query will create a list of MediaItems but with the derived types. (PhotoMediaItem or VideoMediaItem) in a polymorphic way.

Will this query work? I can't really test this code unfortunately because I'm in a migration process.



from Polymorphic entities in Room

No comments:

Post a Comment