org.apache.ibatis.type.JdbcType Java Examples

The following examples show how to use org.apache.ibatis.type.JdbcType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MapperBuilderAssistant.java    From mybatis with Apache License 2.0 7 votes vote down vote up
private Class<?> resolveParameterJavaType(Class<?> resultType, String property, Class<?> javaType, JdbcType jdbcType) {
  if (javaType == null) {
    if (JdbcType.CURSOR.equals(jdbcType)) {
      javaType = java.sql.ResultSet.class;
    } else if (Map.class.isAssignableFrom(resultType)) {
      javaType = Object.class;
    } else {
      MetaClass metaResultType = MetaClass.forClass(resultType);
      javaType = metaResultType.getGetterType(property);
    }
  }
  if (javaType == null) {
    javaType = Object.class;
  }
  return javaType;
}
 
Example #2
Source File: XMLMapperBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void parameterMapElement(List<XNode> list) throws Exception {
  for (XNode parameterMapNode : list) {
    String id = parameterMapNode.getStringAttribute("id");
    String type = parameterMapNode.getStringAttribute("type");
    Class<?> parameterClass = resolveClass(type);
    List<XNode> parameterNodes = parameterMapNode.evalNodes("parameter");
    List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
    for (XNode parameterNode : parameterNodes) {
      String property = parameterNode.getStringAttribute("property");
      String javaType = parameterNode.getStringAttribute("javaType");
      String jdbcType = parameterNode.getStringAttribute("jdbcType");
      String resultMap = parameterNode.getStringAttribute("resultMap");
      String mode = parameterNode.getStringAttribute("mode");
      String typeHandler = parameterNode.getStringAttribute("typeHandler");
      Integer numericScale = parameterNode.getIntAttribute("numericScale");
      ParameterMode modeEnum = resolveParameterMode(mode);
      Class<?> javaTypeClass = resolveClass(javaType);
      JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
      @SuppressWarnings("unchecked")
      Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
      ParameterMapping parameterMapping = builderAssistant.buildParameterMapping(parameterClass, property, javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
      parameterMappings.add(parameterMapping);
    }
    builderAssistant.addParameterMap(id, parameterClass, parameterMappings);
  }
}
 
Example #3
Source File: MapperAnnotationBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void applyConstructorArgs(Arg[] args, Class<?> resultType, List<ResultMapping> resultMappings) {
  for (Arg arg : args) {
    List<ResultFlag> flags = new ArrayList<ResultFlag>();
    flags.add(ResultFlag.CONSTRUCTOR);
    if (arg.id()) {
      flags.add(ResultFlag.ID);
    }
    ResultMapping resultMapping = assistant.buildResultMapping(
        resultType,
        null,
        nullOrEmpty(arg.column()),
        arg.javaType() == void.class ? null : arg.javaType(),
        arg.jdbcType() == JdbcType.UNDEFINED ? null : arg.jdbcType(),
        nullOrEmpty(arg.select()),
        nullOrEmpty(arg.resultMap()),
        null,
        null,
        arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler(),
        flags,
        null,
        null,
        false);
    resultMappings.add(resultMapping);
  }
}
 
Example #4
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareInsertAuthorMappedStatementWithAutoKey(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (username,password,email,bio,favourite_section) values(?,?,?,?,?)"), SqlCommandType.INSERT)
      .parameterMap(
          new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build());
            }
          }).build())
      .cache(authorCache)
      .keyGenerator(new Jdbc3KeyGenerator())
      .keyProperty("id")
      .build();
  return ms;
}
 
Example #5
Source File: MapperAnnotationBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void applyConstructorArgs(Arg[] args, Class<?> resultType, List<ResultMapping> resultMappings) {
  for (Arg arg : args) {
    List<ResultFlag> flags = new ArrayList<ResultFlag>();
    flags.add(ResultFlag.CONSTRUCTOR);
    if (arg.id()) {
      flags.add(ResultFlag.ID);
    }
    ResultMapping resultMapping = assistant.buildResultMapping(
        resultType,
        null,
        nullOrEmpty(arg.column()),
        arg.javaType() == void.class ? null : arg.javaType(),
        arg.jdbcType() == JdbcType.UNDEFINED ? null : arg.jdbcType(),
        nullOrEmpty(arg.select()),
        nullOrEmpty(arg.resultMap()),
        null,
        null,
        arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler(),
        flags,
        null,
        null,
        false);
    resultMappings.add(resultMapping);
  }
}
 
Example #6
Source File: XMLConfigBuilder.java    From QuickProject with Apache License 2.0 6 votes vote down vote up
private void typeHandlerElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        String typeHandlerPackage = child.getStringAttribute("name");
        typeHandlerRegistry.register(typeHandlerPackage);
      } else {
        String javaTypeName = child.getStringAttribute("javaType");
        String jdbcTypeName = child.getStringAttribute("jdbcType");
        String handlerTypeName = child.getStringAttribute("handler");
        Class<?> javaTypeClass = resolveClass(javaTypeName);
        JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
        Class<?> typeHandlerClass = resolveClass(handlerTypeName);
        if (javaTypeClass != null) {
          if (jdbcType == null) {
            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
          } else {
            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
          }
        } else {
          typeHandlerRegistry.register(typeHandlerClass);
        }
      }
    }
  }
}
 
Example #7
Source File: HierarchicalXMLConfigBuilder.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void typeHandlerElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                String typeHandlerPackage = child.getStringAttribute("name");
                typeHandlerRegistry.register(typeHandlerPackage);
            } else {
                String javaTypeName = child.getStringAttribute("javaType");
                String jdbcTypeName = child.getStringAttribute("jdbcType");
                String handlerTypeName = child.getStringAttribute("handler");
                Class<?> javaTypeClass = resolveClass(javaTypeName);
                JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
                Class<?> typeHandlerClass = resolveClass(handlerTypeName);
                if (javaTypeClass != null) {
                    if (jdbcType == null) {
                        typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
                    } else {
                        typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
                    }
                } else {
                    typeHandlerRegistry.register(typeHandlerClass);
                }
            }
        }
    }
}
 
Example #8
Source File: ByteArrayTypeHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
{
    if (parameter == null)
    {
        ps.setNull(i, Types.BINARY);
    }
    else
    {
        try
        {
            ps.setBytes(i, (byte[])parameter);
        }
        catch (Throwable e)
        {
            throw new SerializationException(e);
        }
    }
}
 
Example #9
Source File: MapperAnnotationBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Discriminator applyDiscriminator(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) {
  if (discriminator != null) {
    String column = discriminator.column();
    Class<?> javaType = discriminator.javaType() == void.class ? String.class : discriminator.javaType();
    JdbcType jdbcType = discriminator.jdbcType() == JdbcType.UNDEFINED ? null : discriminator.jdbcType();
    Class<? extends TypeHandler<?>> typeHandler = discriminator.typeHandler() == UnknownTypeHandler.class ? null : discriminator.typeHandler();
    Case[] cases = discriminator.cases();
    Map<String, String> discriminatorMap = new HashMap<String, String>();
    for (Case c : cases) {
      String value = c.value();
      String caseResultMapId = resultMapId + "-" + value;
      discriminatorMap.put(value, caseResultMapId);
    }
    return assistant.buildDiscriminator(resultType, column, javaType, jdbcType, typeHandler, discriminatorMap);
  }
  return null;
}
 
Example #10
Source File: CallableStatementHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void registerOutputParameters(CallableStatement cs) throws SQLException {
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  for (int i = 0, n = parameterMappings.size(); i < n; i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (null == parameterMapping.getJdbcType()) {
        throw new ExecutorException("The JDBC Type must be specified for output parameter.  Parameter: " + parameterMapping.getProperty());
      } else {
        if (parameterMapping.getNumericScale() != null && (parameterMapping.getJdbcType() == JdbcType.NUMERIC || parameterMapping.getJdbcType() == JdbcType.DECIMAL)) {
          cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getNumericScale());
        } else {
          //核心是调用CallableStatement.registerOutParameter
          if (parameterMapping.getJdbcTypeName() == null) {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE);
          } else {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getJdbcTypeName());
          }
        }
      }
    }
  }
}
 
Example #11
Source File: ObjectTypeHandler.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void setParameter(PreparedStatement ps, int parameterIndex, Object parameter, JdbcType arg3) throws SQLException {
  try {
    if (parameter == null) {
      ps.setString(parameterIndex, null);
    }
    else if (parameter instanceof String) {
      ps.setString(parameterIndex, (String) parameter);
    }
    else {
      // Because the value is stored as VARCHAR in the db it has to be transformed to a JSON string
      ps.setString(parameterIndex, mapper.writeValueAsString(parameter));
    }
  } catch (Exception ex) {
    log.error("Error setting a prepared statement parameter from a tag value", ex);
  }
}
 
Example #12
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareUpdateAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "updateAuthor", new StaticSqlSource(config,"UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), SqlCommandType.UPDATE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .cache(authorCache).build();
  return ms;
}
 
Example #13
Source File: XMLMapperBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Discriminator processDiscriminatorElement(XNode context, Class<?> resultType, List<ResultMapping> resultMappings) throws Exception {
  String column = context.getStringAttribute("column");
  String javaType = context.getStringAttribute("javaType");
  String jdbcType = context.getStringAttribute("jdbcType");
  String typeHandler = context.getStringAttribute("typeHandler");
  Class<?> javaTypeClass = resolveClass(javaType);
  @SuppressWarnings("unchecked")
  Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
  JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  Map<String, String> discriminatorMap = new HashMap<String, String>();
  for (XNode caseChild : context.getChildren()) {
    String value = caseChild.getStringAttribute("value");
    String resultMap = caseChild.getStringAttribute("resultMap", processNestedResultMappings(caseChild, resultMappings));
    discriminatorMap.put(value, resultMap);
  }
  return builderAssistant.buildDiscriminator(resultType, column, javaTypeClass, jdbcTypeEnum, typeHandlerClass, discriminatorMap);
}
 
Example #14
Source File: ResultSetWrapper.java    From mybatis with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the type handler to use when reading the result set.
 * Tries to get from the TypeHandlerRegistry by searching for the property type.
 * If not found it gets the column JDBC type and tries to get a handler for it.
 * 
 * @param propertyType
 * @param columnName
 * @return
 */
public TypeHandler<?> getTypeHandler(Class<?> propertyType, String columnName) {
  TypeHandler<?> handler = null;
  Map<Class<?>, TypeHandler<?>> columnHandlers = typeHandlerMap.get(columnName);
  if (columnHandlers == null) {
    columnHandlers = new HashMap<Class<?>, TypeHandler<?>>();
    typeHandlerMap.put(columnName, columnHandlers);
  } else {
    handler = columnHandlers.get(propertyType);
  }
  if (handler == null) {
    handler = typeHandlerRegistry.getTypeHandler(propertyType);
    // Replicate logic of UnknownTypeHandler#resolveTypeHandler
    // See issue #59 comment 10
    if (handler == null || handler instanceof UnknownTypeHandler) {
      final int index = columnNames.indexOf(columnName);
      final JdbcType jdbcType = jdbcTypes.get(index);
      final Class<?> javaType = resolveClass(classNames.get(index));
      if (javaType != null && jdbcType != null) {
        handler = typeHandlerRegistry.getTypeHandler(javaType, jdbcType);
      } else if (javaType != null) {
        handler = typeHandlerRegistry.getTypeHandler(javaType);
      } else if (jdbcType != null) {
        handler = typeHandlerRegistry.getTypeHandler(jdbcType);
      }
    }
    if (handler == null || handler instanceof UnknownTypeHandler) {
      handler = new ObjectTypeHandler();
    }
    columnHandlers.put(propertyType, handler);
  }
  return handler;
}
 
Example #15
Source File: ColumnTypeTest.java    From Mapper with MIT License 5 votes vote down vote up
@Test
public void testJdbcTypeBlob(){
    EntityHelper.initEntityNameMap(UserJdbcTypeBlob.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserJdbcTypeBlob.class);
    Assert.assertNotNull(entityTable);

    Set<EntityColumn> columns = entityTable.getEntityClassColumns();
    Assert.assertEquals(1, columns.size());

    for (EntityColumn column : columns) {
        Assert.assertEquals("name", column.getColumn());
        Assert.assertEquals("name", column.getProperty());

        Assert.assertEquals("name = #{name, jdbcType=BLOB}", column.getColumnEqualsHolder());
        Assert.assertEquals("name = #{record.name, jdbcType=BLOB}", column.getColumnEqualsHolder("record"));
        Assert.assertEquals("#{name, jdbcType=BLOB}", column.getColumnHolder());
        Assert.assertEquals("#{record.name, jdbcType=BLOB}", column.getColumnHolder("record"));
        Assert.assertEquals("#{record.name, jdbcType=BLOB}", column.getColumnHolder("record", "suffix"));
        Assert.assertEquals("#{record.namesuffix, jdbcType=BLOB},", column.getColumnHolder("record", "suffix", ","));
        Assert.assertNull(column.getTypeHandler());
    }

    ResultMap resultMap = entityTable.getResultMap(configuration);
    Assert.assertEquals("[NAME]", resultMap.getMappedColumns().toString());

    Assert.assertEquals(1, resultMap.getResultMappings().size());

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("name", resultMapping.getColumn());
    Assert.assertEquals("name", resultMapping.getProperty());
    Assert.assertNotNull(resultMapping.getJdbcType());
    Assert.assertEquals(JdbcType.BLOB, resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}
 
Example #16
Source File: EncryptedStringTypeHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void setNonNullParameter(
    final PreparedStatement ps,
    final int parameterIndex,
    final String parameter,
    final JdbcType jdbcType) throws SQLException
{
  ps.setString(parameterIndex, encrypt(parameter));
}
 
Example #17
Source File: MetadataTypeHandler.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setParameter(PreparedStatement ps, int parameterIndex, Object metadata, JdbcType arg3) throws SQLException {
  if (metadata != null) {
    ps.setString(parameterIndex, Metadata.toJSON((Metadata) metadata));
  } else {
    ps.setString(parameterIndex, null);
  }
}
 
Example #18
Source File: AlarmConditionTypeHandler.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setParameter(final PreparedStatement ps, final int parameterIndex, final Object alarmCondition, final JdbcType arg3) throws SQLException {
  if (alarmCondition != null) {
    String conditionXml = null;
    try {
      conditionXml = ((AlarmCondition) alarmCondition).toConfigXML();
    } catch (RuntimeException e) {
      LOGGER.error("Unable to encode alarm condition in XML - will be persisted as null.");
    }
    ps.setString(parameterIndex, conditionXml);
  } else {
    ps.setString(parameterIndex, null);
  }
}
 
Example #19
Source File: MapTypeHandler.java    From taskana with Apache License 2.0 5 votes vote down vote up
@Override
public void setNonNullParameter(
    PreparedStatement ps, int i, Map<String, Object> parameter, JdbcType jdbcType)
    throws SQLException {
  if (parameter != null && parameter.size() > 0) {
    LOGGER.debug("Input-Map before serializing: {}", parameter);
    // Convert Map to JSON string
    JSONObject jsonObj = new JSONObject(parameter);
    ps.setString(i, jsonObj.toString());
  } else {
    ps.setNull(i, Types.BLOB);
  }
}
 
Example #20
Source File: FirstNameTypeHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public void setParameter(PreparedStatement ps, int i, Object parameter,
                         JdbcType jdbcType) throws SQLException {
  if (parameter == null) {
    ps.setNull(i, Types.VARCHAR);
  } else {
    Name name = (Name) parameter;
    ps.setString(i, name.getFirstName());
  }
}
 
Example #21
Source File: JSONTypeHandler.java    From mmpt with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
        String parameter, JdbcType jdbcType) throws SQLException {
    PGobject jsonObject = new PGobject();
    jsonObject.setType("json");
    jsonObject.setValue(parameter);
    ps.setObject(i, jsonObject);
}
 
Example #22
Source File: UserStateTypeHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public void setParameter(PreparedStatement ps, int i, Object value, JdbcType jdbcType) throws SQLException {

  String key = "";
  for (Entry<String, String> entry : lookup.entrySet()) {
    if (value.equals(entry.getValue())) {
      key = entry.getKey();
    }
  }
  ps.setInt(i, Integer.valueOf(key));
}
 
Example #23
Source File: JsonTypeHandler.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
        throws SQLException {
    try {
        ps.setString(i, objectMapper.writeValueAsString(parameter));
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: XMLConfigBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void typeHandlerElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      //如果是package
      if ("package".equals(child.getName())) {
        String typeHandlerPackage = child.getStringAttribute("name");
        //(一)调用TypeHandlerRegistry.register,去包下找所有类
        typeHandlerRegistry.register(typeHandlerPackage);
      } else {
        //如果是typeHandler
        String javaTypeName = child.getStringAttribute("javaType");
        String jdbcTypeName = child.getStringAttribute("jdbcType");
        String handlerTypeName = child.getStringAttribute("handler");
        Class<?> javaTypeClass = resolveClass(javaTypeName);
        JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
        Class<?> typeHandlerClass = resolveClass(handlerTypeName);
        //(二)调用TypeHandlerRegistry.register(以下是3种不同的参数形式)
        if (javaTypeClass != null) {
          if (jdbcType == null) {
            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
          } else {
            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
          }
        } else {
          typeHandlerRegistry.register(typeHandlerClass);
        }
      }
    }
  }
}
 
Example #25
Source File: Mapper.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Select("select * from users where id = #{value}")
@Results({
  @Result(column="id", property="id"),
  @Result(column="name", property="name"),
  @Result(column="city", property="city", jdbcType=JdbcType.CHAR),
  @Result(column="state", property="state", jdbcType=JdbcType.VARCHAR)
})
User getUser(Integer id);
 
Example #26
Source File: MapperBuilderAssistant.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public Discriminator buildDiscriminator(
    Class<?> resultType,
    String column,
    Class<?> javaType,
    JdbcType jdbcType,
    Class<? extends TypeHandler<?>> typeHandler,
    Map<String, String> discriminatorMap) {
  ResultMapping resultMapping = buildResultMapping(
      resultType,
      null,
      column,
      javaType,
      jdbcType,
      null,
      null,
      null,
      null,
      typeHandler,
      new ArrayList<ResultFlag>(),
      null,
      null,
      false);
  Map<String, String> namespaceDiscriminatorMap = new HashMap<String, String>();
  for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
    String resultMap = e.getValue();
    resultMap = applyCurrentNamespace(resultMap, true);
    namespaceDiscriminatorMap.put(e.getKey(), resultMap);
  }
  Discriminator.Builder discriminatorBuilder = new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap);
  return discriminatorBuilder.build();
}
 
Example #27
Source File: DefaultParameterHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public void setParameters(PreparedStatement ps) throws SQLException {
  ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  if (parameterMappings != null) {
    //循环设参数
    for (int i = 0; i < parameterMappings.size(); i++) {
      ParameterMapping parameterMapping = parameterMappings.get(i);
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        //如果不是OUT,才设进去
        Object value;
        String propertyName = parameterMapping.getProperty();
        if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
          //若有额外的参数, 设为额外的参数
          value = boundSql.getAdditionalParameter(propertyName);
        } else if (parameterObject == null) {
          //若参数为null,直接设null
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          //若参数有相应的TypeHandler,直接设object
          value = parameterObject;
        } else {
          //除此以外,MetaObject.getValue反射取得值设进去
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        TypeHandler typeHandler = parameterMapping.getTypeHandler();
        JdbcType jdbcType = parameterMapping.getJdbcType();
        if (value == null && jdbcType == null) {
          //不同类型的set方法不同,所以委派给子类的setParameter方法
          jdbcType = configuration.getJdbcTypeForNull();
        }
        typeHandler.setParameter(ps, i + 1, value, jdbcType);
      }
    }
  }
}
 
Example #28
Source File: ApiKeyTokenTypeHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void setNonNullParameter(
    final PreparedStatement ps,
    final int parameterIndex,
    final ApiKeyToken parameter,
    final JdbcType jdbcType) throws SQLException
{
  ps.setString(parameterIndex, encrypt(parameter));
}
 
Example #29
Source File: TreeNodeTypeHandler.java    From mybatis-jackson with MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, TreeNode parameter, JdbcType jdbcType) throws SQLException {
    try {
        ps.setString(i, ReaderWriter.write(parameter));
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}
 
Example #30
Source File: SqlHelper.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 根据类型替换参数
 *
 * 仅作为数字和字符串两种类型进行处理,需要特殊处理的可以继续完善这里
 * @param sql
 * @param value
 * @param jdbcType
 * @param javaType
 * @return
 */
private static String replaceParameter(String sql, Object value, JdbcType jdbcType, Class javaType) {
    String strValue = String.valueOf(value);
    if (jdbcType != null) {
        switch (jdbcType) {
            //数字

            case BIT:
            case TINYINT:
            case SMALLINT:
            case INTEGER:
            case BIGINT:
            case FLOAT:
            case REAL:
            case DOUBLE:
            case NUMERIC:
            case DECIMAL:
                break;
            //日期

            case DATE:
            case TIME:
            case TIMESTAMP:
                //其他,包含字符串和其他特殊类型

            default:
                strValue = "'" + strValue + "'";


        }
    } else if (Number.class.isAssignableFrom(javaType)) {
        //不加单引号

    } else {
        strValue = "'" + strValue + "'";
    }
    return sql.replaceFirst("\\?", strValue);
}