0

I've recently started using LiveData in my project and was facing difficulties JOINing data from related tables. Not being able to find anything related to this on the web - links welcome, please, I started this morning to try and find a solution.

So, I put together a Product Entity class…

@Entity(tableName = "products")
public class Product {
    @PrimaryKey(autoGenerate = true)
    @NonNull
    int productID;

    @NonNull
    private String productName;

    @NonNull
    private String supplierName;
    private int supplierID;
    private int stocklevel;

    public Product(@NonNull String productName, int supplierID) {
        this.productName = productName;
        this.supplierID = supplierID;
        this.supplierName = "Dummy Supplier";
        stocklevel = 0;
}

and a DAO with the query…

    @Query("SELECT products.*, suppliers.supplierName FROM products JOIN suppliers ON products.supplierID = suppliers.supplierID ORDER BY stocklevel DESC")
    LiveData<List<Product>> getProductDetails();

so that, when the query is run, the placeholder text is overwritten by the supplierName from the related table. And it works!

So, my question is, 'Is this an acceptable way of proceeding? And, if not - what is?'

Any feedback? Or links?

oldgit
  • 13
  • 5
  • I think what you are looking is using `@ForeignKey`, does this [question](https://stackoverflow.com/questions/47511750/how-to-use-foreign-key-in-room-persistence-library) help you? – TheLibrarian Oct 22 '22 at 11:20
  • @TheLibrarian - quite possibly - thanks, I'll settle down for a good read. I had done all my searching using terms like JOIN and relationships. The idea of ForeignKey never entered my mind. Doh! – oldgit Oct 22 '22 at 11:27
  • There are easier other ways but ForeignKey is probably the best. – TheLibrarian Oct 22 '22 at 11:37
  • On reflection - and having found the documentation - what I was really looking for was the equivalent of a fairly simple LOOKUP type of approach. And this is easily provided by an Intermediate Data class - see [here](https://developer.android.com/training/data-storage/room/relationships#data-class) – oldgit Oct 23 '22 at 04:32
  • Yeah, I still have half-written answer about that but that example is not your case. Your two entities are strictly tied to each other. – TheLibrarian Oct 23 '22 at 13:38

0 Answers0