'JPA @Convert annotation on a method

The JPA @Convert annotation says it's applicable to a method (as well as field and type).

What is an example of a situation where it is useful?



Solution 1:[1]

@Convert allows us to map JDBC types to Java classes.

Let's consider the code block below:-

public class UserName implements Serializable {

    private String name;
    private String surname;

    // getters and setters
}

@Entity(name = "UserTable")
public class User {
   
    private UserName userName;

    //...
}

Now we need to create a converter that transforms the PersonName attribute to a database column and vice-versa.

Now we can annotate our converter class with @Converter and implement the AttributeConverter interface. Parametrize the interface with the types of the class and the database column, in that order:

@Converter
public class UserNameConverter implements 
  AttributeConverter<UserName, String> {

    private static final String SEPARATOR = ", ";

    @Override
    public String convertToDatabaseColumn(UserName userName) {
        if (userName == null) {
            return null;
        }
....
    }
}

In order to use the converter, we need to add the @Convert annotation to the attribute and specify the converter class we want to use:

@Entity(name = "PersonTable")
public class User {

    @Convert(converter = UserNameConverter.class)
    private UserName userName;
    
    // ...
}

For more details you can refer below:- jpa-convert

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 N K Shukla