Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- /**
- * <result column="location" property="location" jdbcType="VARCHAR" typeHandler="xxx.noscan.EnumAlternativeNameTypeHandler"/>
- *
- * @author Sebastien Lorber <i>(lorber.sebastien@gmail.com)</i>
- * @param <E>
- */
- public class EnumAlternativeNameTypeHandler<E extends Enum<E> & EnumAlternativeName> extends BaseTypeHandler<E> {
- private Class<E> type;
- private Map<String,E> 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<E> type) {
- Preconditions.checkNotNull(type);
- Preconditions.checkNotNull(type.getEnumConstants(),type.getSimpleName() + " does not represent an enum type.");
- List<E> 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);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement