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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With