Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

Best practice of mapping collection of enum

Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • 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
  • 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