Using IntelliJ JPA GUI Tools to Create a @ManyToMany

IntelliJ IDEA Unlimited has awesome JPA GUI database tools. We recently added Tags to our NixMash Spring Posts feature so needed to create a @ManyToMany relationship between our tags and posts tables with a post_tag_ids link table. Here’s the relationship shown in an IntelliJ database view diagram.

The IntelliJ JPA Persistence GUI has a sweet Entity Relationship diagram feature and you might think this is where you would create a nice drag-n-drop relationship, but not so. We start with the Database Schema for our @ManyToMany tags-to-posts relationship to produce fully configured Post and Tag Models.

Now we can create our relationship between the posts and tags tables.

Before moving from this dialog we want to point out a couple of things. 1) Notice the package setting. You’ll want this to match your application location for your new or updated models. And 2) Don’t forget to rename the “Map As” and “Mapped Type” objects to match your model class names.

You’ll also want to confirm all of the fields for your class properties are selected.

Here’s our dialog box where we create our @ManyToMany relationship from the tables.

With that you’re finished. You can start writing code against your @ManyToMany Post and Tag Entities.

Now Chuck the GUI Results

Psych! The IntelliJ Database GUI Tools are awesome, but before signing off you should know that the GUI Schema Generator, like most GUI tools, generates more “stuff” than you might want. Since less is usually best, you might want to create sample models and extract only the elements you want.

For instance, this is the essential code for establishing a @ManyToMany from Post to Tag.

And here in the Tag Model Class.

Much cleaner.


While having transitioned from talking about a GUI to the code, notice in the Post class we’re doing an EAGER fetch. This is because we almost always want to retrieve our tags along with the post object. We’re also placing the annotation on the “tags” property, not the getTags() method. This is because we set Access Type to FIELD and need to place the relationship definition on the tags field. (Access type defaults to where you put your identifier annotation (@Id). If you put it on the field it will be AccessType.FIELD, if you put it on the getter it will be AccessType.PROPERTY.)

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.