A combination of tricks can get you there. You can define an enum that
can be externalized to integers. Then you can define a transient enum
type field in your entity, and another int field that gets mapped to
database. You can use life cycle callback method to populate one from
another. Please see the following code snippet:
enum MyEnum {
MINUS_ONE(-1), ZERO(0);
private int i;
private MyEnum(int i) {this.i = i;}
public int getIntValue() {return i;}
public static MyEnum valueOf(int i) {
for (MyEnum m : values()) {if(m.i == i) return m;}
throw new IllegalArgumentException("No matching constant for " + i);
}
@Override public String toString() {return String.valueOf(i);}
}
@Entity public class Foo {
@Id @GeneratedValue
private int id;
private transient MyEnum anEnum; // the actual enum
@Basic
private int intValueForAnEnum; // gets stored in database
@PrePersist
void populateDBFields() {
intValueForAnEnum = anEnum.getIntValue();
}
@PostLoad
void populateTransientFields() {
anEnum = MyEnum.valueOf(intValueForAnEnum);
}
}
Hope it helps,
Sahoo
glassfish_at_javadesktop.org wrote:
> Hi,
>
> In our database we have an enumeration of strings. All these strings are actually numbers, for example ['-2', '-1' ,'1' ,'2']. At first I wanted to create an enumerator in Java for this but I couldn't find out how to do it, since enumerated values cannot start with a number. Then I thought that I could use an int in my entity bean. This seem to work pretty good but I could still set the attribute to a value which is not in the enumeration. Also, I cannot confirm that all JPA providers would convert these string values to int values in the same way.
>
> Could someone please help me? I would either like to use an enum or int if enum doesn't work. But I only want to use int if the conversion is within the JPA specification, '-2' becomes int with value -2 for example, otherwise I guess I'll have to use String.
>
> Thanks!
>
> Leo
> [Message sent by forum member 'woel' (woel)]
>
> http://forums.java.net/jive/thread.jspa?messageID=240608
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_glassfish.dev.java.net
> For additional commands, e-mail: users-help_at_glassfish.dev.java.net
>
>