Are enums supported by JDBC?

本小妞迷上赌 提交于 2020-03-17 09:53:46

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/3155967/are-enums-supported-by-jdbc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!