Java Code Examples for org.apache.ibatis.type.JdbcType

The following examples show how to use org.apache.ibatis.type.JdbcType. These examples are extracted from open source projects. 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 Project: mybatis   Source File: ExecutorTestHelper.java    License: 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 2
Source Project: mybaties   Source File: MapperAnnotationBuilder.java    License: 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 3
Source Project: mybatis   Source File: MapperBuilderAssistant.java    License: Apache License 2.0 6 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 4
@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 5
Source Project: mybatis   Source File: XMLMapperBuilder.java    License: 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 6
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: 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 7
Source Project: mybatis   Source File: CallableStatementHandler.java    License: 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 8
Source Project: mybaties   Source File: MapperAnnotationBuilder.java    License: 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 9
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 10
Source Project: mybaties   Source File: XMLMapperBuilder.java    License: 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 11
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 12
Source Project: QuickProject   Source File: XMLConfigBuilder.java    License: 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 13
Source Project: mybatis   Source File: MapperAnnotationBuilder.java    License: 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 14
Source Project: mybatis-types   Source File: OffsetDateTimeTypeHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, OffsetDateTime parameter, JdbcType jdbcType) throws SQLException {
    // Postgres do not work with offsets > than 15 hours, maybe other DBs too
    int offset = parameter.get(ChronoField.OFFSET_SECONDS);
    if (Math.abs(offset) > 54000) {
        parameter = parameter.withOffsetSameInstant(ZoneOffset.ofHours(offset > 0 ? 15 : -15));
    }

    ps.setTimestamp(
        i,
        Timestamp.from(parameter.toInstant()),
        GregorianCalendar.from(parameter.toZonedDateTime())
    );
}
 
Example 15
@Override
public void setNonNullParameter(PreparedStatement ps, int i, JsonNode parameter, JdbcType jdbcType) throws SQLException {
    String str = null;
    try {
        str = mapper.writeValueAsString(parameter);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        str = "{}";
    }
    ps.setString(i, str);
}
 
Example 16
Source Project: nexus-public   Source File: DateTimeTypeHandler.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void setNonNullParameter(final PreparedStatement ps,
                                final int parameterIndex,
                                final DateTime parameter,
                                final JdbcType jdbcType)
    throws SQLException
{
  ps.setTimestamp(parameterIndex, new Timestamp(parameter.getMillis()));
}
 
Example 17
Source Project: syhthems-platform   Source File: BaseEnumTypeHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
    if (jdbcType == null) {
        ps.setString(i, parameter.toString());
    } else {
        ps.setObject(i, parameter.getKey(), jdbcType.TYPE_CODE);
    }
}
 
Example 18
Source Project: jframe   Source File: SqlTimestampTypeHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i,
		Long parameter, JdbcType jdbcType) throws SQLException {
	if (parameter == 0L)
		parameter = new Date().getTime();
	ps.setTimestamp(i, new java.sql.Timestamp(parameter));
}
 
Example 19
Source Project: QuickProject   Source File: XMLConfigBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void settingsElement(XNode context) throws Exception {
  if (context != null) {
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    MetaClass metaConfig = MetaClass.forClass(Configuration.class);
    for (Object key : props.keySet()) {
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), true));
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    configuration.setLogImpl(resolveClass(props.getProperty("logImpl")));
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
  }
}
 
Example 20
Source Project: mybatis   Source File: DefaultParameterHandler.java    License: 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 21
Source Project: mybatis   Source File: BaseBuilder.java    License: Apache License 2.0 5 votes vote down vote up
protected JdbcType resolveJdbcType(String alias) {
  if (alias == null) {
    return null;
  }
  try {
    return JdbcType.valueOf(alias);
  } catch (IllegalArgumentException e) {
    throw new BuilderException("Error resolving JdbcType. Cause: " + e, e);
  }
}
 
Example 22
Source Project: maintain   Source File: DeliveryHeadMapper.java    License: MIT License 5 votes vote down vote up
@Results(id = "deliveryHeadResult", value = {
	@Result(property = "headGuid", column = "head_guid", id = true),
	@Result(property = "appType", column = "app_type"),
	@Result(property = "appTime", column = "app_time", jdbcType = JdbcType.TIMESTAMP),
	@Result(property = "appStatus", column = "app_status"),
	@Result(property = "appUid", column = "app_uid"),
	@Result(property = "appUname", column = "app_uname"),
	@Result(property = "appSenderId", column = "app_sender_id"),
	@Result(property = "declTime", column = "decl_time", jdbcType = JdbcType.TIMESTAMP),
	@Result(property = "customsCode", column = "customs_code"),
	@Result(property = "copNo", column = "cop_no"),
	@Result(property = "preNo", column = "pre_no"),
	@Result(property = "rkdNo", column = "rkd_no"),
	@Result(property = "operatorCode", column = "operator_code"),
	@Result(property = "operatorName", column = "operator_name"),
	@Result(property = "ieFlag", column = "ie_flag"),
	@Result(property = "trafMode", column = "traf_mode"),
	@Result(property = "trafNo", column = "traf_no"),
	@Result(property = "voyageNo", column = "voyage_no"),
	@Result(property = "billNo", column = "bill_no"),
	@Result(property = "logisticsCode", column = "logistics_code"),
	@Result(property = "logisticsName", column = "logistics_name"),
	@Result(property = "unloadLocation", column = "unload_location"),
	@Result(property = "note", column = "note"),
	@Result(property = "delFlag", column = "del_flag", jdbcType = JdbcType.INTEGER),
	@Result(property = "msgGuid", column = "msg_guid"),
	@Result(property = "sysDays", column = "sys_days", jdbcType = JdbcType.INTEGER),
	@Result(property = "sysDate", column = "sys_date", jdbcType = JdbcType.TIMESTAMP),
})
@SelectProvider(type = DeliveryHeadSqlProvide.class, method = "getDeliveryHeadListSql")
List<DeliveryHead> getDeliveryHeadList(DeliveryHead deliveryHead);
 
Example 23
Source Project: mybatis-types   Source File: LocalDateTimeTypeHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
    ps.setTimestamp(i,
        Timestamp.valueOf(parameter),
        GregorianCalendar.from(ZonedDateTime.of(parameter, ZoneId.systemDefault()))
    );
}
 
Example 24
Source Project: mybaties   Source File: DefaultParameterHandler.java    License: 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 25
Source Project: mybaties   Source File: MapperBuilderAssistant.java    License: 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 26
Source Project: mybatis-boost   Source File: JsonTypeHandler.java    License: 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 27
Source Project: mybaties   Source File: FirstNameTypeHandler.java    License: 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 28
Source Project: mybaties   Source File: UserStateTypeHandler.java    License: 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 29
Source Project: mmpt   Source File: JSONTypeHandler.java    License: 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 30
/**
 * 设置非空参数
 *
 * @param ps             PreparedStatement
 * @param parameterIndex 参数
 * @param parameter      参数数组
 * @param jdbcType       jdbcType
 * @throws SQLException
 */
@Override
public void setNonNullParameter(PreparedStatement ps, int parameterIndex, T parameter, JdbcType jdbcType)
        throws SQLException {
    String jsonText;
    try {
        jsonText = objectMapper.writeValueAsString(parameter);
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }

    ps.setString(parameterIndex, jsonText);
}