vendredi 13 novembre 2015

How do I create a generic JPA converter for an EnumMap?

I want to create a generic JPA converter to convert an EnumMap into a string and vice versa. At moment I have the following code:

@Converter
public class EnumMapConverter4jpa implements AttributeConverter<EnumMap<?, Object> value ) {
  @Override
  public String convertToDatabaseColumn( EnumMap<?, Object> value ) {
    if ( value == null ) return null;
    String text = "";
    for ( Entry<?, Object> entry : value.entrySet()) {
      text += " " + entry.getKey.toString() + ":" + entry.getValue().toString();
    }
    return ( text.length() > 0 ? text.substring( 2 ) : null );
  }

@Override
public EnumMap<?, Object> convertToEntityAttribute( String value ) {
  if ( value == null ) return null;
  EnumMap<?, Object> emap = null; // TODO instantiate new map here
  String[] elements = value.split( " " );
  for ( String element : elements ) {
    String[] keyval = element.split( ":" );
    System.out.println( keyval[0] + "=" + keyval[1] );
    // TODO: emap.put( key, value );
  }
  return emap;
}

Method convertToDatabaseColumn() works as expected but convertToEntityAttribute() of course is not. The underlying question here is how do I find out which enum is used in the field for which this converter is used?

Please see also How do I find out the enum used in an EnumMap?





Aucun commentaire:

Enregistrer un commentaire