0

I have an enum as shown below :

public enum SocialType {

    Facebook(1L),
    LinkedIn(2L),
    Twitter(3L),
    Skype(14L),
    Blog(16L),
    Google(21L);

    private Long id;

    SocialType(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public static SocialType parse(Long id) {
        SocialType socialType = null; 
        for (SocialType item : SocialType.values()) {
            if (item.getId() == id) {
                socialType = item;
                break;
            }
        }
        return socialType;
    }
}

And I am using this enum in my entity as below (with some additional fields):

private SocialType  socialType ;
public SocialType getSocialType() {
        return SocialType.parse(this.socialType.getId());
    }

    public void setSocialType(SocialType socialType) {
        this.socialType = socialType;
        this.socialType = SocialType.valueOf(socialType.name());
    }

When I save the entity to my database using Hibernate, the value is SocialType is being saved as the Ordinal Value of the Enum. Instead of this, I want to save the id to the DB.

How can I do that ? Please help me.

EDIT

I was still not able to solve it using the earlier given solutions. But found a good tutorial on how to fix this. Sharing it for others benefit.

http://www.gabiaxel.com/2011/01/better-enum-mapping-with-hibernate.html

Yadu Krishnan
  • 3,492
  • 5
  • 41
  • 80
  • You should unit test your code by passing `new Long(1L)` to your parse method. You should use a primitive long here, and not a Long. Or at least use equals() to compare them. – JB Nizet Jun 17 '14 at 17:02
  • For others who face this issue, I find a better blog explaining how to fix this. I solved my problem with this way. http://www.gabiaxel.com/2011/01/better-enum-mapping-with-hibernate.html – Yadu Krishnan Jun 18 '14 at 04:50

0 Answers0