简体   繁体   English

JOOQ 使用转换器将字符串转换为枚举

[英]JOOQ Cast String to Enum with Converter

While looking for a way to cast my String field into an Enum i stubled across the .cast() Method.在寻找一种将我的字符串字段转换为枚举的方法时,我在 .cast .cast()方法中遇到了问题。 When called it throws an SQLDialectNotSupportedException .调用时会抛出SQLDialectNotSupportedException
Dialect has been Set to SQLSERVER2014 in the Context DSLContext create = DSL.using(conn, SQLDialect.SQLSERVER2014); Dialect 已在 Context DSLContext create = DSL.using(conn, SQLDialect.SQLSERVER2014);中设置为SQLSERVER2014 . .
The corresponding line:对应的行:

create.select( ... lecture.DAY_OF_WEEK.cast(DayOfWeek.class), ... );  

The full Error:完整的错误:

org.jooq.exception.SQLDialectNotSupportedException: Type class java.time.DayOfWeek is not supported in dialect null
at org.jooq.impl.DefaultDataType.getDataType(DefaultDataType.java:944)
at org.jooq.impl.DefaultDataType.getDataType(DefaultDataType.java:880)
at org.jooq.impl.AbstractField.cast(AbstractField.java:256)
at de.esteam.lecturedb.jooq.Classes.Startup.getStandardExample(Startup.java:218)
at de.esteam.lecturedb.jooq.Classes.Startup.main(Startup.java:54)

I tried to achieve a conversion to the Enum with a Converter but i cannot get it running.我试图用转换器实现到 Enum 的转换,但我无法让它运行。

Is there a way to get the Converter into the cast() or is there another way to get the String into the Enum I cannot find?有没有办法让转换器进入cast()或者有另一种方法可以让我找不到的 Enum 中的字符串?

You cannot use cast() here because that would require jOOQ to understand how to cast your data type to your custom type in SQL .您不能在此处使用cast() ,因为这需要 jOOQ 了解如何将您的数据类型转换为SQL中的自定义类型。 What you want to do is a client side conversion, and that is achieved ideally using a Converter .您想要做的是客户端转换,理想情况下可以使用Converter来实现。

Once you have implemented your Converter , the recommended way to use it is to attach it to generated code using the code generator: https://www.jooq.org/doc/latest/manual/code-generation/custom-data-types实现Converter后,推荐的使用方法是使用代码生成器将其附加到生成的代码: https://www.jooq.org/doc/latest/manual/code-generation/custom-data-types

<forcedType>
  <userType>java.time.DayOfWeek</userType>
  <converter>com.example.YourConverter</converter>
  <includeExpression>(?i:DAY_OF_WEEK)</includeExpression>
</forcedType>

If that's not an option, you can create a "converted" field reference as follows:如果这不是一个选项,您可以创建一个“转换的”字段引用,如下所示:

// I'm assuming you're storing the data as an INTEGER
DataType<DayOfWeek> type = SQLDataType.INTEGER.asConvertedDataType(new YourConverter());
Field<DayOfWeek> field = DSL.field("{0}", type, lecture.DAY_OF_WEEK);

// And now use that instead
create.select(field)...

But I really recommend attaching the converter to the generated code for most convience.但我真的建议将转换器附加到生成的代码中以获得最方便。

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

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