Win a copy of Spring Boot in Practice this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Best practice of mapping collection of enum

Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I am having a list assoziation to enums:

class User{
List<RoleAsEnum> roles;

As such with O/R this would get mapped with a join to two tables because of the 1:n relation. For enum reasons one could also consider to use a third join-table, so enum-entries aren't repeated inside the enum table all the time.

Never the less I would like to avoid joins (enums are stupid types and I don't consider them as entities but rather as table-column).

I thought about writing a custom converter, so the enum is serialized into a comma separated string, but I think such an encoding as kind of bad practice. Is there maybe a JPA + hibernate homegrown solution for mapping the 1:n(asEnum) relation?

Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I always wrap my enums in persistable enum entities and map those, providing an easy way to get the actual enum out of the enum entity wrapper. For example:

The above gives you a simple 2 table bidirectional one-to-many / many-to-one relationship between an enum and an entity which needs a collection of those enums. All you have to do is fill out the usual rest of the bean stuff as well as a way to manage the wrapper correctly (i.e. to get and set the enum itself inside it).
    Bookmark Topic Watch Topic
  • New Topic