-->
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: map an enum to a lookup table
PostPosted: Sat May 07, 2011 5:04 pm 
Newbie

Joined: Sat May 07, 2011 4:49 pm
Posts: 1
I'm a beginning hibernate user, searching around through the forum is leaving me a little confused how to map an enum in an entity class that is represented in the database as a simple lookup table. I'm looking for a solution using annotations. I'm sure somebody must have solution for this. How do I finish off writing the Address class to have hibernate directly map the addressType property to the enum when I grab a record from the database using annotations? Any pointers would be appreciated.

public enum AddressType {
BILLING, SHIPPING;
}

@Entity
public class Address implements Serializable {
@Id
private Integer id;

private AddressType addressType
}

Database tables:
Address (
id int not null,
address_type_id int not null,
primary key (`id`),
foreign key (`address_type_id`) references address_type (`id`)
)

AddressType (
id int not null,
name varchar(25) not null,
primary key (`id`)
)

insert into AddressType values (1, 'BILLING'),(2,'SHIPPING');


Top
 Profile  
 
 Post subject: Re: map an enum to a lookup table
PostPosted: Mon May 09, 2011 5:27 am 
Newbie

Joined: Thu May 05, 2011 6:33 am
Posts: 16
For enum you can use the annotation @Enumerated(EnumType.STRING) or @Enumerated(EnumType.ORDINAL).

As string are more safetly, with ordinal, remember that the Ordinal Position of your ennum must be always the same and you cannot remove one from you code java so easily.

Remember the count start from 0. So insert into AddressType values (1, 'BILLING'),(2,'SHIPPING'); but public enum AddressType {
BILLING, SHIPPING;
}

Billing is 0 and SHIPPING is 1. So, define the ordinal in your enum as follow.. BILLING (1) and SHIPPING (2).

Another good solution is a mixed solution between Hibernate and your db.

Create a db table with your enum. Make your address table with a 1 to 1 refence to another Table and Create a view where you get the string and annotate you enum with @Enumerated(EnumType.STRING)

_________________
Luca Preziati


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:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.