Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are enums supported by JDBC?

Tags:

java

enums

jdbc

I really can't find a nice enum JDBC mapping example. Is enum actually supported by JDBC?

I am working with MySQL. I have an enum column, and would like to map to some Java enum.

like image 499
Roman Avatar asked Jul 01 '10 07:07

Roman


People also ask

Does Java support enum?

In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).

Are enums passed by reference Java?

In Java you cannot pass any parameters by reference. The only workaround I can think of would be to create a wrapper class, and wrap an enum. Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.

Does MySQL support enums?

In MySQL, an ENUM is a string object whose value is chosen from a list of permitted values defined at the time of column creation. The ENUM data type provides the following advantages: Compact data storage. MySQL ENUM uses numeric indexes (1, 2, 3, …) to represents string values.

What is Java enum?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma.


2 Answers

JDBC does not support enums.

You can convert a string to an enum though, so if you have a Java enum you can do something like

 MyEnum enumVal =  MyEnum.valueOf(rs.getString("EnumColumn")); 

You'll have to keep your java enum and mysql enum in sync though. MyEnum.valueOf() can throw IllegalArgumentException if there's no mapping from the string, or NullPointerException if you get a null value from the db.

like image 143
nos Avatar answered Sep 23 '22 03:09

nos


Here is some generic solution were are using in converting JDBC values to Java enums.

param = Enum.valueOf((Class<? extends Enum>)dbField.getField().getType(), (String) param); 

where param is the value of the field in the db , and the dbField is the java.reflect.util.Field , where to put the value to

like image 37
Roman Avatar answered Sep 25 '22 03:09

Roman