I am in the need of being able to store and retrieve enums from a SQLite database, which I have solved with combined use of a wrapper class and enums, but I feel it's very poorly designed.
Every time I want to add a new item to the list of enums, I have to add it in three different places.
The enum must contain:
Currently it is implemented like this:
public class items
{
public enum types {
FOO(0),
BAR(1),
BAZ(2);
private final int _value;
types(int value){_value = value;}
public int value(){return _value;}
}
public static types Get(int i)
{
switch(i)
{
case 0:
return types.FOO;
case 1:
return types.BAR;
case 2:
return types.BAZ;
default:
return null;
}
}
public static String Get(Typer type)
{
switch(type)
{
case FOO:
return "This is foo!";
case BAR:
return "This is bar!";
case BAZ:
return "This is baz!";
default:
return "No good!";
}
}
}
Is there a better way to handle this?
First of all, in order to save enum values in a relational database using JPA, you don't have to do anything. By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers.
SQLite does support the enum data type, but it is very compact to store the data.
Storing the Raw Value It isn't possible to store an enum in the user's defaults database. We need to convert the value to a type that is supported by the defaults system. The easiest solution is to ask the enum for its raw value and store that value in the user's defaults database.
You can iterate through an enum to access its values. The static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values.
An enum value has FOO.ordinal()
function is a numeric representation of a value. The function returns its number between zero and n-1
where n
- how much enum values do you have. Then you could use types.values()[i]
to retrieve back a value by the number. But you should keep in mind that it's not allowed to reorder or add new enum in the middle, because the numbers will be changed.
Also, you could use types.valueOf("FOO")
and FOO.name()
for a string representation of the enum value. It's safer to use, because it doesn't depend on the declaration order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With