de.schegge.enumconverter.template.ftl Maven / Gradle / Ivy
/**
* @author ${author}
* @version ${version}
*/
package ${package};
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Map;
import java.util.HashMap;
@Converter${autoApply?string('(autoApply=true)','')}
public final class ${enumConverterTypeName} implements AttributeConverter<${enumTypeName}, ${databaseTypeName}> {
private final Map<${enumTypeName}, ${databaseTypeName}> toDatabaseColumn = new HashMap<>();
private final Map<${databaseTypeName}, ${enumTypeName}> toEntityAttribute = new HashMap<>();
public ${enumConverterTypeName}() {
<#list elements as element>
toDatabaseColumn.put(${enumTypeName}.${element.key!""}, ${element.value[0]!""});
#list>
<#list elements as element>
<#list element.value as value>
toEntityAttribute.put(${value!""}, ${enumTypeName}.${element.key!""});
#list>
#list>
}
@Override
public ${databaseTypeName} convertToDatabaseColumn(${enumTypeName} value) {
if (value == null) {
<#if nullKeyForbidden>
throw new IllegalArgumentException("null key is forbidden");
<#else>
return null;
#if>
}
<#if exceptionIfMissing>
return check(value, toDatabaseColumn.get(value));
<#else>
return toDatabaseColumn.get(value);
#if>
}
@Override
public ${enumTypeName} convertToEntityAttribute(${databaseTypeName} value) {
if (value == null) {
<#if nullKeyForbidden>
throw new IllegalArgumentException("null key is forbidden");
<#else>
return null;
#if>
}
<#if exceptionIfMissing>
return check(value, toEntityAttribute.get(value));
<#else>
return toEntityAttribute.get(value);
#if>
}
<#if exceptionIfMissing>
private V check(K key, V value) {
if (value == null) {
throw new IllegalArgumentException("null value is forbidden: " + key);
}
return value;
}
#if>
}