开发者

Java enum to mysql enum in prepared statement

开发者 https://www.devze.com 2022-12-09 13:26 出处:网络
With the regular statement (just statement) 开发者_JAVA技巧I can put java enums into the queries and it works just fine. With prepared statement I can\'t do this ?MySQL treats its enum type as string

With the regular statement (just statement) 开发者_JAVA技巧I can put java enums into the queries and it works just fine. With prepared statement I can't do this ?


MySQL treats its enum type as string for queries. So you should be able to use PreparedStatement.setString() method and pass enum name to it:

preparedStatement.setString(1, MY_ENUM.name());

This assumes, of course, that names for your java and MySQL enums match.

Notice: name() was chosen instead of toString() as, per the docs:

name() This method is designed primarily for use in specialized situations where correctness depends on getting the exact name, which will not vary from release to release.


If you'd prefer to store it as integer (which is more space and performance friendly) you could do this:

preparedStatement.setInt(1, myEnum.ordinal());

This provides simplicity, however, you must be sure not to change the order of the enum elements in code as that will break their relationship with what is stored in the db.

0

精彩评论

暂无评论...
验证码 换一张
取 消