Ad-Hoc type conversion in JOOQ DSL query

246 Views Asked by At

scenario: we store some encrypted data in db as blob. When reading/saving it, we need to decrypt/encrypt it using an external service. because it is actually a spring bean using an external service, we cannot use the code generator like dealing with enums.

I don't want to use dslContext.select(field1, field2.convertFrom).from(TABLE_NAME) because you need to specify every fields of the table.

It is convenient to use dslContext.selectFrom(TABLE_NAME). wonder if any way we can register the converter bean in such query to perform encrypt and decrypt on the fly.

Thanks

Edit: I ended up using a service to encrypt/decrypt the value when it is actually used. Calling an external service is relatively expensive. Sometimes the value isn't used in the request. It may not make sense to always decrypt the value when reading from db using the converter.

1

There are 1 best solutions below

10
Lukas Eder On

because it is actually a spring bean using an external service, we cannot use the code generator like dealing with enums.

Why not? Just because Spring favours dependency injection, and you currently (as of jOOQ 3.15) cannot inject anything into jOOQ Converter and Binding instances, doesn't mean you can't use other means of looking up such a service. Depending on what you have available, you could use some JNDI lookup, or other means to discover that service when needed, from within your Converter.

Another option would be to use a ConverterProvider and register your logic inside of that. That wouldn't produce your custom type inside of jOOQ records, but whenver you convert your blob to your custom data type, e.g. using reflection.

How to access Spring Beans without Dependency Injection?

If you need to access your Spring Beans you don't need Dependency Injection. Simply create the following class and you can get beans from the static method getBean():

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext;
    }
}