Converters

A nice feature is the AttributeConverter. When you persist an object, it can be useful as an interceptor that catches a particular attribute to do some conversion during the serialization versus the database.

For example, we can create a converter to manage the password of a user. The password could be secured through a Base64 algorithm before the persist and after a query.

The converter could be a good pattern to decouple this operation. See now how to do it.

Here is a Citizen entity:

@Entity(name = "citizen")
public class Citizen {
...
private string password;
...
}

This entity has a password. Here's the code to persist the entity:

Citizen citizen = new Citizen();
citizen.setPassword("prova");
entityManager.persist(citizen);

In this case, the password will be put clean into the database. We now register it as encrypted. Here's a converter that ensures the password:

@Converter
public class PasswordConverter implements AttributeConverter<String, String> {
public static String NEVER_DO_IT;

@Override
public String convertToDatabaseColumn(String password) {
if (password != null) {
String newPassword = getEncoder().encodeToString(password.getBytes());
NEVER_DO_IT = newPassword;
return newPassword;
else return null;
}

@Override
public String convertToEntityAttribute(String password) {
if (password != null) {
return new String(getDecoder().decode(password));
} else return null;
}
}

The converter is declared by the @Converter annotation and implements the JPA interface AttributeConverter so it can override the main two methods.

convertToDatabaseColumn is used when the field is put in the database. So we will encrypt our password, when convertToEntityAttribute is the result from a query from the database. In this case, we decrypt the password and provide it.

Because we want the password field to be intercepted by the converter, we can annotate the password field of the Citizen specifying the converter class:

@Convert(converter = PasswordConverter.class)
private String password;

In the end during the query or persist operation, we will always work with the clean password, but the real registered password in the database can be seen in the NEVER_DO_IT field. It will be something like cHJvdmE=.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.72