import xxx.EnumAlternativeName;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
*
*
* @author Sebastien Lorber (lorber.sebastien@gmail.com)
* @param
*/
public class EnumAlternativeNameTypeHandler & EnumAlternativeName> extends BaseTypeHandler {
private Class type;
private Map mappedByAlternativeName;
public EnumAlternativeNameTypeHandler() {
throw new IllegalStateException("" +
"You are trying to use a EnumAlternativeNameTypeHandler without declaring the javaType." +
"Read the EnumAlternativeNameTypeHandler javadoc for details! " +
"If this happens, it may be because ");
}
public EnumAlternativeNameTypeHandler(Class type) {
Preconditions.checkNotNull(type);
Preconditions.checkNotNull(type.getEnumConstants(),type.getSimpleName() + " does not represent an enum type.");
List enums = Lists.newArrayList(type.getEnumConstants());
this.type = type;
this.mappedByAlternativeName = Maps.uniqueIndex(enums,EnumAlternativeName.GET_ALTERNATIVE_NAME);
}
private E getEnumConstFromAlternativeName(String alternativeName) {
if ( alternativeName == null ) {
return null;
} else {
E enumConst = mappedByAlternativeName.get(alternativeName);
Preconditions.checkNotNull(enumConst,"No enum could be found for "+type+" with alternative name " + alternativeName);
return enumConst;
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
if (jdbcType == null) {
ps.setString(i, parameter.getAlternativeName() );
} else {
ps.setObject(i, parameter.getAlternativeName() , jdbcType.TYPE_CODE);
}
}
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
String s = rs.getString(columnName);
return getEnumConstFromAlternativeName(s);
}
@Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String s = rs.getString(columnIndex);
return getEnumConstFromAlternativeName(s);
}
@Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String s = cs.getString(columnIndex);
return getEnumConstFromAlternativeName(s);
}
}