Home > Enterprise >  How to implement a JPA AttributeConverter for handling NULL properly?
How to implement a JPA AttributeConverter for handling NULL properly?

Time:07-15

I have written a JPA attribute converter to convert values between java.lang.String and java.nio.Path.

The converter works fine for non-null value. In case of converting null from the Java world to SQL, Hibernate inserts the string value null into the database row. But I would to have (SQL) NULL, so that the column is either empty or in case of NOT NULL contraint a constraint violation will be caused.

What do I wrong?

The converter looks like this:

@Converter
public class PathConverter 
  implements AttributeConverter<Path, String> {
  @Override
  public String convertToDatabaseColumn(Path path) {
    return Objects.toString(path);
  }

  @Override
  public Path convertToEntityAttribute(String columnValue) {
    return Optional.ofNullable(columnValue)
                   .map(Paths::get).orElse(null);
  }
}

I am using Spring Boot 2.7.1 with Hibernate for my application.

CodePudding user response:

Change:

public String convertToDatabaseColumn(Path path) {
   return Objects.toString(path);
}

To:

 public String convertToDatabaseColumn(Path path) {
    return path == null ? null : Objects.toString(path);
  }

because Objects.toString() return the string "null" if the value is null

From the documentation:

Returns the result of calling toString for a non-null argument and "null" for a null argument.

  • Related