Jpalite

Many2Many

The OrmLite ManyToMany sample is reworked as the Jpalite many2many-example project. The original sample appears in the ormlite-jdbc test sources in the com.j256.ormlite.jdbc.examples.manytomany package. The readme text explains:

"This shows how you can use a join table to implement many-to-many type of object layout." If you compare the entity classes between both implementations, you will see the main difference is in the annotations used, with JPA perhaps being more succinct using @Column, @OneToOne and @OneToMany. Using custom queries to see results is also gone.

In the Many2Many main resources is the persistence.xml JPA configuration file. It defines the following persistence unit attributes:

  • name = manytomany
  • classes User, Post and UserPost
  • database-name = manytomany.db

Note the database is configured as in-memory, so the database name is not relevant unless there is a switch to an on-disk database.

Run the many2many-example as a Java Application from the ManyToManyMain class static main() and the expected console output will ba as follows.

Console output

PostsByUser:
Jim Coakley posted "Wow is it cold outside!!" & "Now it's a bit warmer thank goodness."
UsersByPosts:
Only Jim Coakley posted "Wow is it cold outside!!"
Both Jim Coakley and Gandalf Gray posted "Now it's a bit warmer thank goodness."
Test completed successfully

Many to Many Association

We have users posting text messages which can be shared among the users. We need to find which posts have been dispatched by a single user and which users have shared a single post. This is known as a many to many association between users and posts and requires a "join table" to capture this association.

The Jpalite solution is to create 2 back-to-back one-to-many associations with the join table. The following code snippet shows the fields of the User entity class

User fields

Entity "UserPost" represents the join table and it identifies each user and post combination using just their ids. A User "getPosts()" method is provided to extract just the posts from the @OneToMany-annotated "userPosts" field. There is also an "addPost()" method.