0

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?

johnlon
  • 167
  • 1
  • 11
  • read this https://stackoverflow.com/questions/594597/hibernate-annotations-which-is-better-field-or-property-access – grigouille Mar 14 '22 at 09:47

1 Answers1

-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

N K Shukla
  • 288
  • 1
  • 3
  • 12
  • Yes but ... My question was about when @Convert would-be used on a MEtHOD not a field. If you look at the annotation it can be used if a field or type it method. – johnlon Mar 12 '22 at 12:41