How to create and register AttributeConverter dynamically

Viewed 33

I write a Spring Boot starter. There is some logic which required AttributeConverter for my service. Is it possible to create it in the starter and register it in hibernate?

1 Answers

You can enable the AttributeConverter gloablly for all entity attributes of the given type using @Converter(autoApply = true):

@Converter(autoApply = true) // important
public class FooConverter implements AttributeConverter<Foo, String> {
 
    @Override
    public String convertToDatabaseColumn(Foo attribute) {
        // ...
    }
 
    @Override
    public Color convertToEntityAttribute(String dbData) {
        // ..
    }
}

However, this assumes there is only one converter for said type. If you have multiple, different converts in let's say different spring-boot-starter dependencies, you can active a specific converter for the service using Hibernate @ConverterRegistration:

@org.hibernate.annotations.ConverterRegistration(converter=com.company.entitiy.FooConverter.class, autoApply=true)
package com.company.entitiy;

If you want even more granular configuration, you can configure the converter on each entity attribute separately, such as:

@Entity
public class Bar {

    @Convert(converter = FooConverter.class)
    private Foo foo;
    
    // ...
}
Related