我想创建一个通用的JPA转换器,将EnumMap转换为字符串,反之亦然。我现在有以下代码:
@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;
}
方法convertToDatabaseColumn()按预期工作,但convertToEntityAttribute()当然不是。这里的基本问题是如何找出在使用此转换器的字段中使用哪个枚举?