简体   繁体   English

使用JOOQ在运行时指定数据类型

[英]Specifying datatype at runtime using JOOQ

I am using JOOQ to generate the SQL from the JAVA object. 我正在使用JOOQ从JAVA对象生成SQL。 Below is my code- 以下是我的代码-

String tableName = "tabel1";
String columnName = "column1";
String dataType = "varchar";

CreateTableAsStep<Record> createStmt = create.createTable(tableName).column(columnName, dataType);

It's not allowing to set the string datatype. 不允许设置字符串数据类型。 But using SQLDatatype, I am getting only enumerated list of datatypes, which I have to supply at compile time only. 但是使用SQLDatatype时,我仅获得枚举的数据类型列表,而这些列表仅在编译时提供。 Is it possible to set the datatype at runtime or any way to get the enumerated type using string name. 是否可以在运行时设置数据类型或使用字符串名称以任何方式获取枚举类型。

Any help is appreciated. 任何帮助表示赞赏。

The confusion here might be what really happens at "runtime". 这里的困惑可能是“运行时”真正发生的事情。 If you have a variable in Java, such as: 如果您在Java中有一个变量,例如:

DataType<?> dataType = SQLDataType.VARCHAR;

This doesn't mean that this value is set in stone. 这并不意味着此值是固定的。 You can modify it dynamically at runtime , eg by letting the user choose from a dropdown what the data type really is. 您可以在运行时动态修改它,例如,让用户从下拉列表中选择数据类型是什么。 For instance, you could do something like: 例如,您可以执行以下操作:

Map<String, DataType<?>> choices = new LinkedHashMap<>();
choices.put("integer", SQLDataType.INTEGER);
choices.put("timestamp", SQLDataType.TIMESTAMP);
choices.put("varchar", SQLDataType.VARCHAR);

And then supply that to your jOOQ statement as such: 然后像这样将其提供给您的jOOQ语句:

String tableName = "tabel1";
String columnName = "column1";
String dataType = "varchar";

create.createTable(tableName).column(columnName, choices.get(dataType))...;

Do remember that even if writing jOOQ statements feels like static SQL, it is really dynamic SQL. 请记住,即使编写jOOQ语句感觉就像是静态SQL,它实际上也是动态SQL。 You are constructing a SQL statement via the jOOQ API dynamically at runtime. 您正在通过jOOQ API在运行时动态构造SQL语句。 All elements involved with statement creation can be changed dynamically. 语句创建涉及的所有元素都可以动态更改。

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

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