More CDI Alignments
In JPA 2.1, EntityListener supports @Inject(some persistence providers are still problematic). JPA 2.2 adds injection support in @AttributeConverter.
Let's reuse the sample codes in my Java EE 7 sample.
The following is the original version for JPA 2.1, which is used to convert a tag list to string in database.
@Converter
public class ListToStringConveter implements AttributeConverter<List<String>, String> {
@Override
public String convertToDatabaseColumn(List<String> attribute) {
if (attribute == null || attribute.isEmpty()) {
return "";
}
return StringUtils.join(attribute, ",");
}
@Override
public List<String> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.trim().length() == 0) {
return new ArrayList<String>();
}
String[] data = dbData.split(",");
return Arrays.asList(data);
}
}Extract the processing to a standalone CDI bean.
The new tag converter looks like.
Apply it in the entity class.
In the above use @Convert to apply it on tags field.
According to JPA 2.2 specification, this should work.
Attribute converter classes in Java EE environments support dependency injection through the Contexts and Dependency Injection API (CDI) [ 7 ] when CDI is enabled[51]. An attribute converter class that makes use of CDI injection may also define lifecycle callback methods annotated with the PostConstruct and PreDestroy annotations. These methods will be invoked after injection has taken place and before the attribute converter instance is destroyed respectively.
NOTE, But it does not work at the moment, see the issue description in details on stackoverflow.
Grab the source codes from my GitHub account, and have a try.
Last updated
Was this helpful?