简体   繁体   中英

Java enum to mysql enum in prepared statement

With the regular statement (just statement) 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM