AttributeConverter Missing @Converter Annotation

ID

java.jpa_converter_missing_annotation

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Java

Tags

hibernate, jpa, orm

Description

Reports classes that implement AttributeConverter but lack the @Converter annotation. Without @Converter, the persistence provider will not register the converter automatically, and it must be referenced explicitly in every @Convert usage. This is almost always an oversight.

Rationale

The @Converter annotation registers the class with the persistence provider so that it can be applied automatically or referenced by name. Omitting it means the converter is effectively invisible to the JPA runtime unless explicitly wired via @Convert(converter = …​) on each field, which is error-prone.

// Bad: implements AttributeConverter but no @Converter
public class BooleanToStringConverter
    implements AttributeConverter<Boolean, String> {

    public String convertToDatabaseColumn(Boolean attribute) {
        return attribute != null && attribute ? "Y" : "N";
    }

    public Boolean convertToEntityAttribute(String dbData) {
        return "Y".equals(dbData);
    }
}

Remediation

Add the @Converter annotation to the class. Use autoApply = true if the converter should apply to all fields of the matching type automatically.

// Good: @Converter present
@Converter(autoApply = true)
public class BooleanToStringConverter
    implements AttributeConverter<Boolean, String> {

    public String convertToDatabaseColumn(Boolean attribute) {
        return attribute != null && attribute ? "Y" : "N";
    }

    public Boolean convertToEntityAttribute(String dbData) {
        return "Y".equals(dbData);
    }
}