What is the best way to implement many-to-many relationships using ORMLite?

前端 未结 3 966
清酒与你
清酒与你 2020-12-29 06:27

I\'m currently playing with ORMlite to make a model with tables and relationships. One relationship is a many-to-many relationship. What\'s the best way to implement that?

3条回答
  •  一个人的身影
    2020-12-29 06:34

    @Romain's self answer is correct but here's some more information for posterity. As he mentions there is an example many-to-many ORMLite project that demonstrates the best way to do this:

    http://ormlite.com/docs/example-many

    The example uses a join table with the id's of both of the objects to store a relationship. In @Romain's question, the join object would have both the Product and the Purchase object. Something like:

    public class ProductPurchase {
        @DatabaseField(generatedId = true)
        private int id;
        @DatabaseField(foreign = true)
        private Product product;
        @DatabaseField(foreign = true)
        private Purchase purchase;
        ...
    }
    

    The id fields get extracted from the objects which creates a table like:

    CREATE TABLE `userpost` (`id` INTEGER AUTO_INCREMENT , `user_id` INTEGER ,
        `post_id` INTEGER , PRIMARY KEY (`id`) ) 
    

    You then use inner queries to find the Product objects associated with each Purchase and vice versa. See lookupPostsForUser() method in the example project for the details.

    There has been some thought and design work around doing this automatically but right now ORMLite only handles one-to-many relationships internally.

提交回复
热议问题