java JDBC 是否支持枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3155967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are enums supported by JDBC?
提问by Roman
I really can't find a nice enum JDBC mapping example. Is enum actually supported by JDBC?
我真的找不到一个很好的枚举 JDBC 映射示例。JDBC 是否真的支持枚举?
I am working with MySQL. I have an enum column, and would like to map to some Java enum.
我正在使用 MySQL。我有一个枚举列,想映射到一些 Java 枚举。
回答by nos
JDBC does not support enums.
JDBC 不支持枚举。
You can convert a string to an enum though, so if you have a Java enum you can do something like
不过,您可以将字符串转换为枚举,因此如果您有 Java 枚举,则可以执行以下操作
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.
不过,您必须保持 java 枚举和 mysql 枚举同步。如果没有来自字符串的映射,MyEnum.valueOf() 可以抛出 IllegalArgumentException,或者如果从数据库中获得空值,则抛出 NullPointerException。
回答by Roman
Here is some generic solution were are using in converting JDBC values to Java enums.
这是将 JDBC 值转换为 Java 枚举时使用的一些通用解决方案。
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
其中 param 是 db 中字段的值,而 dbField 是 java.reflect.util.Field ,将值放在何处

