简体   繁体   English

Java枚举到预编译语句中的mysql枚举

[英]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. 使用常规语句(只是声明),我可以将java枚举放入查询中,它可以正常工作。 With prepared statement I can't do this ? 准备好的声明我不能这样做?

MySQL treats its enum type as string for queries. MySQL将其枚举类型视为查询字符串。 So you should be able to use PreparedStatement.setString() method and pass enum name to it: 所以你应该能够使用PreparedStatement.setString()方法并将枚举名称传递给它:

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

This assumes, of course, that names for your java and MySQL enums match. 当然,这假定您的java和MySQL枚举的名称匹配。

Notice: name() was chosen instead of toString() as, per the docs: 注意:根据文档,选择name()而不是toString() as:

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. name() 此方法主要用于特殊情况,其中正确性取决于获取确切名称,不会因发行版本而异。

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()); 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. 这提供了简单性,但是,您必须确保不要更改代码中枚举元素的顺序,因为这会破坏它们与db中存储的内容的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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