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

The following are top voted examples for showing how to use org.apache.ibatis.type.JdbcType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: taskana   File: MapTypeHandler.java   Source Code and License 7 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Map parameter, JdbcType jdbcType) throws SQLException {
    if (parameter != null && parameter.size() > 0) {
        LOGGER.debug("Input-Map before serializing: ", parameter);
        // Convert Map to byte array
        try (ByteArrayOutputStream byteOut = new ByteArrayOutputStream()) {
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(parameter);
            ps.setBlob(i, new ByteArrayInputStream(byteOut.toByteArray()));
            out.close();
        } catch (IOException e) {
            LOGGER.error("During serialization of 'customAttributes' an error occured: ", e);
        }
    } else {
        ps.setNull(i, Types.BLOB);
    }
}
 
Example 2
Project: mark-framework   File: ArrayTypeHandler.java   Source Code and License 7 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object[] parameter,
                                JdbcType jdbcType) throws SQLException {

    String typeName = null;
    if (parameter instanceof Integer[]) {
        typeName = TYPE_NAME_INTEGER;
    } else if (parameter instanceof String[]) {
        typeName = TYPE_NAME_VARCHAR;
    } else if (parameter instanceof Boolean[]) {
        typeName = TYPE_NAME_BOOLEAN;
    } else if (parameter instanceof Double[]) {
        typeName = TYPE_NAME_NUMERIC;
    }

    if (typeName == null) {
        throw new TypeException("ArrayTypeHandler parameter typeName error, your type is " + parameter.getClass().getName());
    }

    // 这3行是关键的代码,创建Array,然后ps.setArray(i, array)就可以了
    Connection conn = ps.getConnection();
    Array array = conn.createArrayOf(typeName, parameter);
    ps.setArray(i, array);
}
 
Example 3
Project: MybatisCode   File: ExecutorTestHelper.java   Source Code and License 7 votes vote down vote up
public static MappedStatement prepareInsertAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (id,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, "id", registry.getTypeHandler(int.class)).build());
                  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).build();
  return ms;
}
 
Example 4
Project: mybatis   File: ExecutorTestHelper.java   Source Code and License 7 votes vote down vote up
public static MappedStatement prepareSelectAuthorViaOutParams(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthorViaOutParams", new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT)
      .statementType(StatementType.CALLABLE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>())
      .cache(authorCache).build();
  return ms;
}
 
Example 5
Project: mybatis-plus-mini   File: MybatisXMLMapperBuilder.java   Source Code and License 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<>();
        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 6
Project: mybatis-plus-mini   File: MybatisXMLMapperBuilder.java   Source Code and License 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<>();
    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 7
Project: mybatis-plus-mini   File: MybatisXMLMapperBuilder.java   Source Code and License 6 votes vote down vote up
private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) throws Exception {
    String property;
    if (flags.contains(ResultFlag.CONSTRUCTOR)) {
        property = context.getStringAttribute("name");
    } else {
        property = context.getStringAttribute("property");
    }
    String column = context.getStringAttribute("column");
    String javaType = context.getStringAttribute("javaType");
    String jdbcType = context.getStringAttribute("jdbcType");
    String nestedSelect = context.getStringAttribute("select");
    String nestedResultMap = context.getStringAttribute("resultMap",
            processNestedResultMappings(context, Collections.<ResultMapping>emptyList()));
    String notNullColumn = context.getStringAttribute("notNullColumn");
    String columnPrefix = context.getStringAttribute("columnPrefix");
    String typeHandler = context.getStringAttribute("typeHandler");
    String resultSet = context.getStringAttribute("resultSet");
    String foreignColumn = context.getStringAttribute("foreignColumn");
    boolean lazy = "lazy".equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
    Class<?> javaTypeClass = resolveClass(javaType);
    @SuppressWarnings("unchecked")
    Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
    return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
}
 
Example 8
Project: mybatis-plus-mini   File: MybatisMapperAnnotationBuilder.java   Source Code and License 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();
        @SuppressWarnings("unchecked")
        Class<? extends TypeHandler<?>> typeHandler = (Class<? extends TypeHandler<?>>) (discriminator.typeHandler() == UnknownTypeHandler.class ? null
                : discriminator.typeHandler());
        Case[] cases = discriminator.cases();
        Map<String, String> discriminatorMap = new HashMap<>();
        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
Project: mybatis-plus-mini   File: MybatisXMLConfigBuilder.java   Source Code and License 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 10
Project: alfresco-core   File: SerializableTypeHandler.java   Source Code and License 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, SerializableTypeHandler.serializableType);
    }
    else
    {
        try
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(parameter);
            byte[] bytes = baos.toByteArray();
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ps.setBinaryStream(i, bais, bytes.length);
        }
        catch (Throwable e)
        {
            throw new SerializationException(e);
        }
    }
}
 
Example 11
Project: alfresco-core   File: ByteArrayTypeHandler.java   Source Code and License 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 12
Project: alfresco-core   File: HierarchicalXMLConfigBuilder.java   Source Code and License 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
Project: taskana   File: AttachmentMapper.java   Source Code and License 6 votes vote down vote up
@Select("SELECT ID, TASK_ID, CREATED, MODIFIED, CLASSIFICATION_KEY, REF_COMPANY, REF_SYSTEM, REF_INSTANCE, REF_TYPE, REF_VALUE, CHANNEL, RECEIVED, CUSTOM_ATTRIBUTES "
    + "FROM ATTACHMENT "
    + "WHERE TASK_ID = #{taskId}")
@Results(value = {
    @Result(property = "id", column = "ID"),
    @Result(property = "taskId", column = "TASK_ID"),
    @Result(property = "created", column = "CREATED"),
    @Result(property = "modified", column = "MODIFIED"),
    @Result(property = "classification", column = "CLASSIFICATION_KEY", javaType = Classification.class,
        one = @One(select = CLASSIFICATION_FINDBYID)),
    @Result(property = "objectReference.company", column = "REF_COMPANY"),
    @Result(property = "objectReference.system", column = "REF_SYSTEM"),
    @Result(property = "objectReference.systemInstance", column = "REF_INSTANCE"),
    @Result(property = "objectReference.type", column = "REF_TYPE"),
    @Result(property = "objectReference.value", column = "REF_VALUE"),
    @Result(property = "channel", column = "CHANNEL"),
    @Result(property = "received", column = "RECEIVED"),
    @Result(property = "customAttributes", column = "CUSTOM_ATTRIBUTES", jdbcType = JdbcType.BLOB,
        javaType = Map.class, typeHandler = MapTypeHandler.class),
})
List<AttachmentImpl> findAttachmentsByTaskId(@Param("taskId") String taskId);
 
Example 14
Project: easyadmin   File: AdminUserMapper.java   Source Code and License 6 votes vote down vote up
@Select({
        "select",
        "u.id, u.name, u.email, u.creator, u.flag, u.last_login_time,c.name createUser",
        "from admin_user u LEFT JOIN admin_user c ON u.creator=c.id",
        "where u.name LIKE #{query} LIMIT #{begin},#{pagesize}"
})
@Results({
        @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
        @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
        @Result(column="psw", property="psw", jdbcType= JdbcType.VARCHAR),
        @Result(column="email", property="email", jdbcType= JdbcType.VARCHAR),
        @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
        @Result(column="flag", property="flag", jdbcType= JdbcType.INTEGER),
        @Result(column="last_login_time", property="lastLoginTime", jdbcType= JdbcType.TIMESTAMP)
})
List<AdminUser> select(@Param("begin") int begin, @Param("pagesize") int pageSize, @Param("query") String query);
 
Example 15
Project: easyadmin   File: MenuMapper.java   Source Code and License 6 votes vote down vote up
@SelectProvider(type=MenuSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
    @Result(column="url", property="url", jdbcType= JdbcType.VARCHAR),
    @Result(column="icon", property="icon", jdbcType= JdbcType.VARCHAR),
    @Result(column="menu_type", property="menuType", jdbcType= JdbcType.CHAR),
    @Result(column="display", property="display", jdbcType= JdbcType.INTEGER),
    @Result(column="parent_id", property="parentId", jdbcType= JdbcType.INTEGER),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP),
    @Result(column="update_user", property="updateUser", jdbcType= JdbcType.INTEGER),
    @Result(column="update_time", property="updateTime", jdbcType= JdbcType.TIMESTAMP),
    @Result(column="status", property="status", jdbcType= JdbcType.CHAR)
})
List<Menu> selectByExample(MenuCriteria example);
 
Example 16
Project: MybatisCode   File: MapperAnnotationBuilder.java   Source Code and License 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();
    @SuppressWarnings("unchecked")
    Class<? extends TypeHandler<?>> typeHandler = (Class<? extends 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 17
Project: MybatisCode   File: MapperBuilderAssistant.java   Source Code and License 6 votes vote down vote up
public ParameterMapping buildParameterMapping(
    Class<?> parameterType,
    String property,
    Class<?> javaType,
    JdbcType jdbcType,
    String resultMap,
    ParameterMode parameterMode,
    Class<? extends TypeHandler<?>> typeHandler,
    Integer numericScale) {
  resultMap = applyCurrentNamespace(resultMap, true);

  // Class parameterType = parameterMapBuilder.type();
  Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
  TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);

  return new ParameterMapping.Builder(configuration, property, javaTypeClass)
      .jdbcType(jdbcType)
      .resultMapId(resultMap)
      .mode(parameterMode)
      .numericScale(numericScale)
      .typeHandler(typeHandlerInstance)
      .build();
}
 
Example 18
Project: MybatisCode   File: XMLMapperBuilder.java   Source Code and License 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 19
Project: mybatis   File: ExecutorTestHelper.java   Source Code and License 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 20
Project: MybatisCode   File: XMLConfigBuilder.java   Source Code and License 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 21
Project: MybatisCode   File: DefaultParameterHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void setParametersThrowsProperException() throws SQLException {
  final MappedStatement mappedStatement = getMappedStatement();
  final Object parameterObject = null;
  final BoundSql boundSql = mock(BoundSql.class);

  TypeHandler<String> typeHandler = mock(TypeHandler.class);
  doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), anyString(), any(JdbcType.class));
  ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", typeHandler).build();
  List<ParameterMapping> parameterMappings = Collections.singletonList(parameterMapping);
  when(boundSql.getParameterMappings()).thenReturn(parameterMappings);

  DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);

  PreparedStatement ps = mock(PreparedStatement.class);
  try {
    defaultParameterHandler.setParameters(ps);
    Assert.fail("Should have thrown TypeException");
  } catch (Exception e) {
    Assert.assertTrue("expected TypeException", e instanceof TypeException);
    Assert.assertTrue("", e.getMessage().contains("mapping: ParameterMapping"));
  }

}
 
Example 22
Project: Shop-for-JavaWeb   File: XMLMapperBuilder.java   Source Code and License 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 23
Project: mybatis   File: ExecutorTestHelper.java   Source Code and License 6 votes vote down vote up
public static MappedStatement prepareInsertAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (id,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, "id", registry.getTypeHandler(int.class)).build());
                  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).build();
  return ms;
}
 
Example 24
Project: MybatisCode   File: ExecutorTestHelper.java   Source Code and License 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 25
Project: MybatisCode   File: ExecutorTestHelper.java   Source Code and License 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 26
Project: MybatisCode   File: ExecutorTestHelper.java   Source Code and License 6 votes vote down vote up
public static MappedStatement prepareSelectAuthorViaOutParams(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthorViaOutParams", new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT)
      .statementType(StatementType.CALLABLE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>())
      .cache(authorCache).build();
  return ms;
}
 
Example 27
Project: spring-boot-sample   File: XMLConfigBuilder.java   Source Code and License 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 28
Project: mybatis-beetl-scripting   File: ParameterHandlerFunction.java   Source Code and License 6 votes vote down vote up
@Override
public Object call(Object[] paras, Context ctx) {
    if (null == paras || paras.length == 0)
        throw new RuntimeException("param.paras[0] must not be empty!");

    Configuration configuration = (Configuration) ctx.getGlobal("_configuration");
    List<ParameterMapping> parameterMappings = (List<ParameterMapping>) ctx.getGlobal("_parameterMappings");
    Map<String, Object> params = (Map<String, Object>) ctx.getGlobal("_params");

    String jdbcType = paras.length > 1 ? (String) paras[1] : null, javaType = paras.length > 2 ? (String) paras[2] : null;
    String property = "_PARAM_" + parameterMappings.size();
    params.put(property, paras[0]);
    Class<?> javaTypeClass;
    try {
        javaTypeClass = null != javaType ? Class.forName(javaType) : (null == paras[0] ? Object.class : paras[0].getClass());
    } catch (ClassNotFoundException e) {
        javaTypeClass = (null == paras[0] ? Object.class : paras[0].getClass());
    }
    ParameterMapping parameterMapping = new ParameterMapping.Builder(configuration, property, javaTypeClass)
            .jdbcTypeName(jdbcType)
            .jdbcType(null != jdbcType ? JdbcType.valueOf(jdbcType) : null).build();

    parameterMappings.add(parameterMapping);

    return "?";
}
 
Example 29
Project: mybatis   File: MapperBuilderAssistant.java   Source Code and License 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, configuration.getReflectorFactory());
      javaType = metaResultType.getGetterType(property);
    }
  }
  if (javaType == null) {
    javaType = Object.class;
  }
  return javaType;
}
 
Example 30
Project: mybatis   File: MapperBuilderAssistant.java   Source Code and License 6 votes vote down vote up
/** Backward compatibility signature */
public ResultMapping buildResultMapping(
    Class<?> resultType,
    String property,
    String column,
    Class<?> javaType,
    JdbcType jdbcType,
    String nestedSelect,
    String nestedResultMap,
    String notNullColumn,
    String columnPrefix,
    Class<? extends TypeHandler<?>> typeHandler,
    List<ResultFlag> flags) {
    return buildResultMapping(
      resultType, property, column, javaType, jdbcType, nestedSelect,
      nestedResultMap, notNullColumn, columnPrefix, typeHandler, flags, null, null, configuration.isLazyLoadingEnabled());
}
 
Example 31
Project: mybatis   File: XMLMapperBuilder.java   Source Code and License 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 32
Project: mybatis   File: XMLConfigBuilder.java   Source Code and License 6 votes vote down vote up
private void settingsElement(Properties props) throws Exception {
  configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
  configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
  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.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), 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 33
Project: mybatis   File: DefaultParameterHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void setParametersThrowsProperException() throws SQLException {
  final MappedStatement mappedStatement = getMappedStatement();
  final Object parameterObject = null;
  final BoundSql boundSql = mock(BoundSql.class);

  TypeHandler<String> typeHandler = mock(TypeHandler.class);
  doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), anyString(), any(JdbcType.class));
  ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", typeHandler).build();
  List<ParameterMapping> parameterMappings = Collections.singletonList(parameterMapping);
  when(boundSql.getParameterMappings()).thenReturn(parameterMappings);

  DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);

  PreparedStatement ps = mock(PreparedStatement.class);
  try {
    defaultParameterHandler.setParameters(ps);
    Assert.fail("Should have thrown TypeException");
  } catch (Exception e) {
    Assert.assertTrue("expected TypeException", e instanceof TypeException);
    Assert.assertTrue("", e.getMessage().contains("mapping: ParameterMapping"));
  }

}
 
Example 34
Project: mybatis-plus-mini   File: MybatisMapperAnnotationBuilder.java   Source Code and License 5 votes vote down vote up
private void applyResults(Result[] results, Class<?> resultType, List<ResultMapping> resultMappings) {
    for (Result result : results) {
        List<ResultFlag> flags = new ArrayList<>();
        if (result.id()) {
            flags.add(ResultFlag.ID);
        }
        @SuppressWarnings("unchecked")
        Class<? extends TypeHandler<?>> typeHandler = (Class<? extends TypeHandler<?>>)
                ((result.typeHandler() == UnknownTypeHandler.class) ? null : result.typeHandler());
        ResultMapping resultMapping = assistant.buildResultMapping(
                resultType,
                nullOrEmpty(result.property()),
                nullOrEmpty(result.column()),
                result.javaType() == void.class ? null : result.javaType(),
                result.jdbcType() == JdbcType.UNDEFINED ? null : result.jdbcType(),
                hasNestedSelect(result) ? nestedSelectId(result) : null,
                null,
                null,
                null,
                typeHandler,
                flags,
                null,
                null,
                isLazy(result));
        resultMappings.add(resultMapping);
    }
}
 
Example 35
Project: mybatis-plus-mini   File: MybatisMapperAnnotationBuilder.java   Source Code and License 5 votes vote down vote up
private void applyConstructorArgs(Arg[] args, Class<?> resultType, List<ResultMapping> resultMappings) {
    for (Arg arg : args) {
        List<ResultFlag> flags = new ArrayList<>();
        flags.add(ResultFlag.CONSTRUCTOR);
        if (arg.id()) {
            flags.add(ResultFlag.ID);
        }
        @SuppressWarnings("unchecked")
        Class<? extends TypeHandler<?>> typeHandler = (Class<? extends TypeHandler<?>>)
                (arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler());
        ResultMapping resultMapping = assistant.buildResultMapping(
                resultType,
                nullOrEmpty(arg.name()),
                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,
                typeHandler,
                flags,
                null,
                null,
                false);
        resultMappings.add(resultMapping);
    }
}
 
Example 36
Project: mybatis-plus-mini   File: MybatisXMLConfigBuilder.java   Source Code and License 5 votes vote down vote up
private void settingsElement(Properties props) throws Exception {
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    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"), false));
    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.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), 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.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    @SuppressWarnings("unchecked")
    Class<? extends Log> logImpl = (Class<? extends Log>) resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
}
 
Example 37
Project: alfresco-core   File: HierarchicalXMLConfigBuilder.java   Source Code and License 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, localReflectorFactory);
        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.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), 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")));
    }
}
 
Example 38
Project: lemon-mybatis-plus   File: ArrayTypeHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
	StringBuilder arrayBuilder = new StringBuilder();
	if (parameter != null && parameter.length>0) {
        for(String val: parameter){
        	arrayBuilder.append(",");
        	arrayBuilder.append(val);
        }
        arrayBuilder.deleteCharAt(0);
    }
    ps.setString(i, arrayBuilder.toString());
}
 
Example 39
Project: easyadmin   File: RoleMapper.java   Source Code and License 5 votes vote down vote up
@SelectProvider(type=RoleSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="update_time", property="updateTime", jdbcType= JdbcType.TIMESTAMP),
    @Result(column="update_user", property="updateUser", jdbcType= JdbcType.INTEGER),
    @Result(column="description", property="description", jdbcType= JdbcType.VARCHAR)
})
List<Role> selectByExample(RoleCriteria example);
 
Example 40
Project: easyadmin   File: RoleMapper.java   Source Code and License 5 votes vote down vote up
@Select({
        "select",
        "r.id, r.name, r.create_time, r.creator,u.name as creator, r.description",
        "from role r LEFT JOIN admin_user u ON r.creator=u.id",
        "where r.name like #{query} LIMIT #{begin},#{pagesize}"
})
@Results({
        @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
        @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
        @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP),
        @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
        @Result(column="description", property="description", jdbcType= JdbcType.VARCHAR)
})
List<Role> select(@Param("begin") int begin, @Param("pagesize") int pageSize, @Param("query") String query);
 
Example 41
Project: easyadmin   File: AdminUserMapper.java   Source Code and License 5 votes vote down vote up
@SelectProvider(type=AdminUserSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
    @Result(column="psw", property="psw", jdbcType= JdbcType.VARCHAR),
    @Result(column="email", property="email", jdbcType= JdbcType.VARCHAR),
    @Result(column="update_time", property="updateTime", jdbcType= JdbcType.TIMESTAMP),
    @Result(column="update_user", property="updateUser", jdbcType= JdbcType.INTEGER),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="flag", property="flag", jdbcType= JdbcType.INTEGER),
    @Result(column="last_login_time", property="lastLoginTime", jdbcType= JdbcType.TIMESTAMP)
})
List<AdminUser> selectByExample(AdminUserCriteria example);
 
Example 42
Project: easyadmin   File: MenuMapper.java   Source Code and License 5 votes vote down vote up
@Select({"SELECT m.id, m.name, m.url, m.icon, m.menu_type, m.display, m.parent_id, m.status,",
        "r.roleid FROM menu m LEFT JOIN (SELECT roleid,menuid FROM role_menu WHERE roleid=#{roleid})",
        " r ON m.id=r.menuid "})
@Results({
        @Result(column="parent_id", property="parentId", jdbcType= JdbcType.INTEGER)
})
List<Menu> selectByRoleId(int roleId);
 
Example 43
Project: easyadmin   File: MenuMapper.java   Source Code and License 5 votes vote down vote up
/**
 *查询用户有权限的菜单列表
 * @param userid
 * @return
 */
@Select({"SELECT id, name, url, icon, menu_type, display, parent_id FROM menu WHERE id IN(",
        "SELECT menuid FROM role_menu WHERE roleid IN ",
        "(SELECT roleid FROM user_role WHERE userid=#{userid}) OR roleid=-1) AND menu_type<>'2' AND `status`='1'"})
@Results({
        @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
        @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
        @Result(column="url", property="url", jdbcType= JdbcType.VARCHAR),
        @Result(column="icon", property="icon", jdbcType= JdbcType.VARCHAR),
        @Result(column="menu_type", property="menuType", jdbcType= JdbcType.CHAR),
        @Result(column="display", property="display", jdbcType= JdbcType.INTEGER),
        @Result(column="parent_id", property="parentId", jdbcType= JdbcType.INTEGER),
        @Result(column="status", property="status", jdbcType= JdbcType.CHAR)
})
List<Menu> selectByUser(int userid);
 
Example 44
Project: easyadmin   File: UserRoleMapper.java   Source Code and License 5 votes vote down vote up
@SelectProvider(type=UserRoleSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="userid", property="userid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="roleid", property="roleid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP)
})
List<UserRole> selectByExample(UserRoleCriteria example);
 
Example 45
Project: easyadmin   File: UserRoleMapper.java   Source Code and License 5 votes vote down vote up
@Select({"SELECT r.id, r.name, r.create_time, r.creator, r.description,u.name creatorUser,u1.userid ",
    "FROM role r LEFT JOIN admin_user u ON r.creator=u.id",
    " LEFT JOIN (SELECT roleid,userid FROM user_role WHERE userid=#{userId}) u1 ON r.id=u1.roleid  "})
@Results({
        @Result(column="id", property="id", jdbcType= JdbcType.INTEGER, id=true),
        @Result(column="name", property="name", jdbcType= JdbcType.VARCHAR),
        @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP),
        @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
        @Result(column="description", property="description", jdbcType= JdbcType.VARCHAR),
        @Result(column = "creatorUser",property = "creatorUser",jdbcType = JdbcType.INTEGER)
})
List<Role> selectByUserId(int userId);
 
Example 46
Project: easyadmin   File: UserRoleMapper.java   Source Code and License 5 votes vote down vote up
@Select({
    "select",
    "userid, roleid, creator, create_time",
    "from user_role",
    "where userid = #{userid,jdbcType=INTEGER}",
      "and roleid = #{roleid,jdbcType=INTEGER}"
})
@Results({
    @Result(column="userid", property="userid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="roleid", property="roleid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP)
})
UserRole selectByPrimaryKey(@Param("userid") Integer userid, @Param("roleid") Integer roleid);
 
Example 47
Project: easyadmin   File: RoleMenuMapper.java   Source Code and License 5 votes vote down vote up
@SelectProvider(type=RoleMenuSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="menuid", property="menuid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="roleid", property="roleid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="flag", property="flag", jdbcType= JdbcType.INTEGER),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP)
})
List<RoleMenu> selectByExample(RoleMenuCriteria example);
 
Example 48
Project: easyadmin   File: RoleMenuMapper.java   Source Code and License 5 votes vote down vote up
@Select({
    "select",
    "menuid, roleid, flag, creator, create_time",
    "from role_menu",
    "where menuid = #{menuid,jdbcType=INTEGER}",
      "and roleid = #{roleid,jdbcType=INTEGER}"
})
@Results({
    @Result(column="menuid", property="menuid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="roleid", property="roleid", jdbcType= JdbcType.INTEGER, id=true),
    @Result(column="flag", property="flag", jdbcType= JdbcType.INTEGER),
    @Result(column="creator", property="creator", jdbcType= JdbcType.INTEGER),
    @Result(column="create_time", property="createTime", jdbcType= JdbcType.TIMESTAMP)
})
RoleMenu selectByPrimaryKey(@Param("menuid") Integer menuid, @Param("roleid") Integer roleid);
 
Example 49
Project: mybatis-generator-plugin   File: SqlHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 通过命名空间方式获取sql
 * @param session
 * @param namespace
 * @param params
 * @return
 */
public static String getNamespaceSql(SqlSession session, String namespace, Object params) {
    Configuration configuration = session.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
    TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    BoundSql boundSql = mappedStatement.getBoundSql(params);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    String sql = boundSql.getSql();
    if (parameterMappings != null) {
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (params == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
                    value = params;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(params);
                    value = metaObject.getValue(propertyName);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                sql = replaceParameter(sql, value, jdbcType, parameterMapping.getJavaType());
            }
        }
    }
    return sql;
}
 
Example 50
Project: mybatis-generator-plugin   File: SqlHelper.java   Source Code and License 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);
}
 
Example 51
Project: ssm-server   File: UserMapper.java   Source Code and License 5 votes vote down vote up
@SelectProvider(type=UserSqlProvider.class, method="selectByExample")
@Results({
    @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
    @Result(column="username", property="username", jdbcType=JdbcType.VARCHAR),
    @Result(column="password", property="password", jdbcType=JdbcType.VARCHAR),
    @Result(column="role", property="role", jdbcType=JdbcType.INTEGER)
})
List<User> selectByExample(UserExample example);
 
Example 52
Project: china-district-syscode   File: SysCodeMapper.java   Source Code and License 5 votes vote down vote up
/**
 * This method was generated by MyBatis Generator.
 * This method corresponds to the database table SysCode
 *
 * @mbggenerated Wed Jul 12 20:57:03 CST 2017
 */
@Select({
    "select",
    "codeId, codeTypeId, codeName, parentCodeId",
    "from SysCode",
    "where codeId = #{codeId,jdbcType=INTEGER}"
})
@Results({
    @Result(column="codeId", property="codeId", jdbcType=JdbcType.INTEGER, id=true),
    @Result(column="codeTypeId", property="codeTypeId", jdbcType=JdbcType.INTEGER),
    @Result(column="codeName", property="codeName", jdbcType=JdbcType.VARCHAR),
    @Result(column="parentCodeId", property="parentCodeId", jdbcType=JdbcType.INTEGER)
})
SysCode selectByPrimaryKey(Integer codeId);
 
Example 53
Project: spring-boot-starter-dao   File: GlobalEnumTypeHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
	if (jdbcType == null) {
		ps.setObject(i, mapEnum.get(parameter));
	} else {
		ps.setObject(i, mapEnum.get(parameter), jdbcType.TYPE_CODE); // see
																		// r3589
	}
}
 
Example 54
Project: asura   File: DefaultParameterHandler.java   Source Code and License 5 votes vote down vote up
public void setParameters(PreparedStatement ps) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.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) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                TypeHandler typeHandler = parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                typeHandler.setParameter(ps, i + 1, value, jdbcType);
            }
        }
    }
}
 
Example 55
Project: jsf-core   File: ConvertableEnumTypeHandler.java   Source Code and License 5 votes vote down vote up
final public void setNonNullParameter(PreparedStatement ps, int i,
        S parameter, JdbcType jdbcType) throws SQLException {
    T v;
    try {
        v = convertableContext.value(parameter);
    } catch (Exception e) {
        throw new SQLException(e.getMessage(), e);
    }
    if (v == null) {
        ps.setNull(i, jdbcType.TYPE_CODE);
    } else {
        delegator.setValue(ps, i, v);
    }
}
 
Example 56
Project: dropwizard-mybatis   File: ESTDateTypeHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i,
        Object o, JdbcType jdbcType) throws SQLException {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_WITH_Z);
    sdf.setTimeZone(TimeZone.getTimeZone(TIMEZONE));
    if (o instanceof Date) {
        preparedStatement.setObject(i, sdf.format((Date) o), Types.TIMESTAMP);
    } else {
        throw new IllegalArgumentException("Object value is not a valid Date: " + o.toString());
    }
}
 
Example 57
Project: k-framework   File: SqlBuilderUtils.java   Source Code and License 5 votes vote down vote up
static String fieldExpression(String fieldName, Column annotation) {
    StringBuilder sb = new StringBuilder("#{").append(fieldName);
    if (null != annotation) {
        if (!JdbcType.UNDEFINED.equals(annotation.jdbcType())) {
            sb.append(",jdbcType=").append(annotation.jdbcType().name());
        }
        if (!UnknownTypeHandler.class.equals(annotation.typeHandler())) {
            sb.append(",typeHandler=").append(annotation.typeHandler().getCanonicalName());
        }
    }
    sb.append("}");
    return sb.toString();
}
 
Example 58
Project: flowable-engine   File: IdmEngineConfigurator.java   Source Code and License 5 votes vote down vote up
@Override
protected List<CustomMyBatisTypeHandlerConfig> getMybatisTypeHandlers() {
    return Collections.singletonList(new CustomMyBatisTypeHandlerConfig(
            ByteArrayRef.class,
            JdbcType.VARCHAR,
            ByteArrayRefTypeHandler.class));
}
 
Example 59
Project: MybatisCode   File: MapperAnnotationBuilder.java   Source Code and License 5 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);
    }
    @SuppressWarnings("unchecked")
    Class<? extends TypeHandler<?>> typeHandler = (Class<? extends TypeHandler<?>>)
            (arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler());
    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,
        typeHandler,
        flags,
        null,
        null,
        false);
    resultMappings.add(resultMapping);
  }
}
 
Example 60
Project: MybatisCode   File: MapperBuilderAssistant.java   Source Code and License 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);
  }
  return new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap).build();
}