-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: Mapping enums
PostPosted: Mon Mar 23, 2009 4:40 am 
Newbie

Joined: Mon Oct 16, 2006 10:23 am
Posts: 8
In the documentation I found 'user types' to map an enum onto a varchar ( http://www.hibernate.org/265.html ) and onto a smallint column ( http://www.hibernate.org/312.html )

Am I correct that when using annotations, these user types are not neccessary? The @Enumerated annotation ( http://www.hibernate.org/hib_docs/annot ... le/#d0e342 ) seems to do the job fine.

If so, it might make sense to update those pages to mention that more prominently.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Mar 23, 2009 9:22 am 
Newbie

Joined: Fri Oct 03, 2008 2:30 am
Posts: 16
Location: Neuchâtel, Switzerland
Yes, you're right. Using @Enumerated you don't have to use an user type for saving an enumeration. But there are some caveats:

1) @Enumerated(EnumType.STRING)
Saving an enumeration as string is little waste of storage space and you tying your database to the name of the enumeration constant. Refactoring a constants name breaks existing data.

2) @Enumerated(EnumType.ORDINAL)
Saves an implementation detail of the enumeration. The ordinal of an enumeration constant is defined as its position in its enumeration declaration.
So changing the position of a constant will have catastrophic consequences.
Additionally there is a little waste of storage space, because an int will be used, whereas in most cases a tinyint is big enough.

I'm using always an user type (using java.sql.Types.TINYINT) to persist enumerations looking like this. So I keep full control of what is written to the storage.

Code:
public enum MyEnum {
  FIRST((byte) 0),
  SECOND((byte) 1);

  private Byte value;

  private MyEnum(byte value) {
    this.value = value;
  }

  public Byte getValue() {
    return value;
  }

  public static MyEnum fromValue(Object value) {
    if (null == value || !(value instanceof Byte))
      return null;

    switch ((Byte) value) {
      case 0:
        return FIRST;
      case 1:
        return SECOND;
    }
    throw new IllegalArgumentException();
  }
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
cron
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.