简体   繁体   English

jOOQ:获取枚举字段时,如果值无法映射,如何确保它抛出异常

[英]jOOQ: when fetching into a Enum field, how to ensure it throws an exception if the value cannot mapped

We use jOOQ 3.15.4 with Spring Boot 2.6.2我们使用 jOOQ 3.15.4 和 Spring Boot 2.6.2

We have an enum stored as a string in database.我们有一个枚举作为字符串存储在数据库中。 It looks like this in the generated code:在生成的代码中看起来像这样:

public final TableField<StatusRecord, String> STATUS = createField(DSL.name("status"), SQLDataType.VARCHAR(255).nullable(false), this, "");

When reading it, we fetch into an object with @Column annotations:在阅读它时,我们使用@Column注释获取 object :

@Column(name = "status")
StatusEnum status

The behavior we see is that when we have a string in DB that does not correspond to any value of the enum, the status field in the object that we map into is null.我们看到的行为是,当我们在 DB 中有一个与枚举的任何值都不对应的字符串时,我们 map 进入的 object 中的status字段是 null。

Is there a way to have this type safe, and have a MappingException thrown when the string cannot be mapped to the enum, like the standard behavior of the valueOf method of an enum?有没有办法让这种类型安全,并在字符串无法映射到枚举时抛出MappingException ,就像枚举的valueOf方法的标准行为一样?

The topic has been discussed a few times in jOOQ's issue tracker, mailing list, etc. There's a pending feature request to change the current behaviour of ignoring inconvertible values to throwing exceptions, see eg https://github.com/jOOQ/jOOQ/issues/3377该主题已在 jOOQ 的问题跟踪器、邮件列表等中讨论过几次。有一个待处理的功能请求来更改忽略不可转换值的当前行为以引发异常,请参阅例如https://github.com/jOOQ/jOOQ/问题/3377

It wasn't easy to do in the past without breaking compatibility as the conversions were implemented in static methods.过去要做到不破坏兼容性并不容易,因为转换是在 static 方法中实现的。 But since jOOQ 3.14, we have a ConverterProvider SPI , so it might be possible to make this configurable, and gradually move towards a fail-fast strategy.但是从 jOOQ 3.14 开始,我们有了一个ConverterProvider SPI ,因此可以使其可配置,并逐渐转向快速失败的策略。

Having said so, you can implement your own ConverterProvider and add such checks to it.话虽如此,您可以实现自己的ConverterProvider并向其添加此类检查。 Alternatively, you can attach a custom Converter to your Field using code generation configuration , and let it throw whenever an invalid value is mapped.或者,您可以使用代码生成配置将自定义Converter附加到您的Field ,并在映射无效值时让它抛出。

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

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