org.apache.ibatis.mapping.MappedStatement Java Examples

The following examples show how to use org.apache.ibatis.mapping.MappedStatement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PaginationHandler.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void init() {
    if (!inited) {
        rowSelectionBuilder.setDefaultPageSize(paginationConfig.getDefaultPageSize());

        if (paginationConfig.enableCountCache()) {
            this.countStatementCache = CacheBuilder.<String, MappedStatement>newBuilder()
                    .concurrencyLevel(Runtime.getRuntime().availableProcessors())
                    .expireAfterWrite(paginationConfig.getCountCacheExpireInSeconds())
                    .initialCapacity(paginationConfig.getCountCacheInitCapacity())
                    .maxCapacity(paginationConfig.getCountCacheMaxCapacity()).build();
            this.countSuffix = (Strings.isBlank(paginationConfig.getCountSuffix()) ? "_COUNT" : paginationConfig.getCountSuffix().trim());
        }
        inited = true;
    }
}
 
Example #2
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
private MappedStatement cloneMappedStatement(MappedStatement old, BoundSql boundSql){
	MappedStatement.Builder builder = new MappedStatement.Builder(
			old.getConfiguration(), old.getId(), new AlwaySqlSource(
					boundSql), old.getSqlCommandType());
       builder.cache(old.getCache());
       builder.databaseId(old.getDatabaseId());
       builder.fetchSize(old.getFetchSize());
       builder.flushCacheRequired(old.isFlushCacheRequired());
       builder.keyGenerator(old.getKeyGenerator());
       builder.keyProperty(join(old.getKeyProperties()));
       builder.keyColumn(join(old.getKeyColumns()));
       builder.lang(old.getLang());
       builder.resource(old.getResource());
       builder.resultMaps(old.getResultMaps());
       builder.resultSetType(old.getResultSetType());
       builder.parameterMap(old.getParameterMap());
       builder.statementType(old.getStatementType());
       builder.timeout(old.getTimeout());
       builder.useCache(old.isUseCache());
       builder.resultOrdered(old.isResultOrdered());
       builder.resulSets(join(old.getResulSets()));

       return builder.build();
}
 
Example #3
Source File: AnnotationStatementScanner.java    From mybatis-jpa with Apache License 2.0 6 votes vote down vote up
public void scan() {
  for (String basePackage : basePackages) {
    Reflections reflections = new Reflections(basePackage, new TypeAnnotationsScanner(),
        new SubTypesScanner(), new MethodAnnotationsScanner());
    Set<Class<?>> mappers = reflections.getTypesAnnotatedWith(Mapper.class);
    for (Class<?> mapperClass : mappers) {
      Method[] methods = mapperClass.getMethods();
      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
          StatementFactory statementFactory = annotationStatementRegistry
              .findFactory(annotation.annotationType());
          if (statementFactory != null) {
            MappedStatement statement = statementFactory.parseStatement(configuration, method, mapperClass);
            configuration.addMappedStatement(statement);
          }
        }

      }
    }
  }
  parsePendingMethods();
}
 
Example #4
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDeleteAuthor() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(101, null, null, null, null, null);
    MappedStatement deleteStatement = ExecutorTestHelper.prepareDeleteAuthorMappedStatement(config);
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
    int rows = executor.update(deleteStatement, author);
    List<Author> authors = executor.query(selectStatement, 101, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(0, authors.size());
    assertTrue(1 == rows || BatchExecutor.BATCH_UPDATE_RETURN_VALUE == rows);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #5
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 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 #6
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSelectDiscriminatedPost() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectDiscriminatedPost(config);
    List<Map<String,String>> products = executor.query(selectStatement, null, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    assertEquals(5, products.size());
    for (Map<String,String> m : products) {
      if ("IMAGES".equals(m.get("SECTION"))) {
        assertNull(m.get("subject"));
      } else {
        assertNotNull(m.get("subject"));
      }
    }
  } finally {
    executor.close(false);
  }
}
 
Example #7
Source File: BaseExecutorTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInsertNewAuthorByProc() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    Author author = new Author(97, "someone", "******", "[email protected]", null, null);
    MappedStatement insertStatement = ExecutorTestHelper.prepareInsertAuthorProc(config);
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectOneAuthorMappedStatement(config);
    int rows = executor.update(insertStatement, author);
    List<Author> authors = executor.query(selectStatement, 97, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    executor.rollback(true);
    assertEquals(1, authors.size());
    assertEquals(author.toString(), authors.get(0).toString());
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #8
Source File: SimpleExecutor.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入的是null
    StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.update
    return handler.update(stmt);
  } finally {
    closeStatement(stmt);
  }
}
 
Example #9
Source File: CachingExecutor.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
    throws SQLException {
  Cache cache = ms.getCache();
  //默认情况下是没有开启缓存的(二级缓存).要开启二级缓存,你需要在你的 SQL 映射文件中添加一行: <cache/>
  //简单的说,就是先查CacheKey,查不到再委托给实际的执行器去查
  if (cache != null) {
    flushCacheIfRequired(ms);
    if (ms.isUseCache() && resultHandler == null) {
      ensureNoOutParams(ms, parameterObject, boundSql);
      @SuppressWarnings("unchecked")
      List<E> list = (List<E>) tcm.getObject(cache, key);
      if (list == null) {
        list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
        tcm.putObject(cache, key, list); // issue #578 and #116
      }
      return list;
    }
  }
  return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
 
Example #10
Source File: BatchExecutor.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example #11
Source File: PageResultInterceptor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 目标对象转换
    ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();

    // 获取MappedStatement,Configuration对象
    MetaObject metaObject =
            MetaObject.forObject(resultSetHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");
    String statement = mappedStatement.getId();
    if (!isPageSql(statement,metaObject.getValue("boundSql.parameterObject"))) {
        return invocation.proceed();
    }

    // 获取分页参数
    QPageQuery pageQuery = (QPageQuery) metaObject.getValue("boundSql.parameterObject");

    List<PageResult> result = new ArrayList<PageResult>(1);
    PageResult page = new PageResult();
    page.setPagination(pageQuery.getPagination());
    page.setResult((List) invocation.proceed());
    result.add(page);

    return result;
}
 
Example #12
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFetchPostsForBlog() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectBlog = ExecutorTestHelper.prepareComplexSelectBlogMappedStatement(config);
    MappedStatement selectPosts = ExecutorTestHelper.prepareSelectPostsForBlogMappedStatement(config);
    config.addMappedStatement(selectBlog);
    config.addMappedStatement(selectPosts);
    List<Post> posts = executor.query(selectPosts, 1, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    executor.flushStatements();
    assertEquals(2, posts.size());
    assertTrue(posts.get(1) instanceof Proxy);
    assertNotNull(posts.get(1).getBlog());
    assertEquals(1, posts.get(1).getBlog().getId());
    executor.rollback(true);
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #13
Source File: UpdateStatementFactory.java    From mybatis-jpa with Apache License 2.0 6 votes vote down vote up
@Override
public MappedStatement parseStatement(Configuration configuration, Method method,
    Class<?> targetClass) {
  String resourceName = targetClass.toString();

  if (!configuration.isResourceLoaded(resourceName)) {
    configuration.addLoadedResource(resourceName);
  }
  String targetClassName = targetClass.getName();
  Class<?> type = super.recognizeEntityType(method, targetClass);
  LanguageDriver languageDriver = Constant.XML_LANGUAGE_DRIVER;
  SqlSource sqlSource = languageDriver
      .createSqlSource(configuration, "<script> " + parseSQL(method, type) + "</script>",
          Object.class);
  String statementId = targetClassName + "." + method.getName();
  MappedStatement.Builder builder = new MappedStatement.Builder(configuration, statementId,
      sqlSource, SqlCommandType.UPDATE);
  builder.resource(super.recognizeResource(targetClassName)).lang(languageDriver)
      .statementType(StatementType.PREPARED);

  return builder.build();
}
 
Example #14
Source File: HaloInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    // 获取第一个参数,MappedStatement
    MappedStatement mappedStatement = (MappedStatement) args[0];
    // 获取第二个参数,该参数类型根据Mapper方法的参数决定,如果是一个参数,则为实体或简单数据类型;如果是多个参数,则为Map。
    Object param = args.length > 1 ? args[1] : null;
    BoundSql boundSql = mappedStatement.getSqlSource().getBoundSql(param);
    String sql = WHITE_SPACE_BLOCK_PATTERN.matcher(boundSql.getSql()).replaceAll(" ");
    if (!props.isShowSlowLog()) {
        return warpIntercept(invocation, mappedStatement, sql, param);
    }
    long start = System.currentTimeMillis();
    Object result = warpIntercept(invocation, mappedStatement, sql, param);
    long end = System.currentTimeMillis();
    long time = end - start;
    if (time > props.getSlowThreshold().toMillis()) {
        logSqlInfo(mappedStatement.getConfiguration(), boundSql, sql, mappedStatement.getId(), time);
    }
    return result;
}
 
Example #15
Source File: BaseExecutorTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSelectAllAuthorsAutoMapped() throws Exception {
  
  Executor executor = createExecutor(new JdbcTransaction(ds, null, false));
  try {
    MappedStatement selectStatement = ExecutorTestHelper.prepareSelectAllAuthorsAutoMappedStatement(config);
    List<Author> authors = executor.query(selectStatement, null, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
    assertEquals(2, authors.size());
    Author author = authors.get(0);
    // id,username, password, email, bio, favourite_section
    // (101,'jim','********','[email protected]','','NEWS');
    assertEquals(101, author.getId());
    assertEquals("jim", author.getUsername());
    assertEquals("[email protected]", author.getEmail());
    assertEquals("", author.getBio());
    assertEquals(Section.NEWS, author.getFavouriteSection());
  } finally {
    executor.rollback(true);
    executor.close(false);
  }
}
 
Example #16
Source File: PageInterceptor.java    From Zebra with Apache License 2.0 6 votes vote down vote up
private Object queryLimit(Invocation invocation, Object[] args, MappedStatement ms, BoundSql boundSql, RowBounds rb)
		throws InvocationTargetException, IllegalAccessException {
	String limitSql = dialect.getLimitSql(boundSql.getSql(), rb.getOffset(), rb.getLimit());
	BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), limitSql, boundSql.getParameterMappings(),
			boundSql.getParameterObject());
	MetaObject mo = (MetaObject) ReflectionUtils.getFieldValue(boundSql, "metaParameters");
	ReflectionUtils.setFieldValue(newBoundSql, "metaParameters", mo);

	args[0] = buildMappedStatement(ms, new SqlSourceWrapper(newBoundSql), ms.getId() + "_LIMIT",
			ms.getResultMaps());
	args[2] = new RowBounds();
	args[3] = null;

	try {
		DaoContextHolder.setSqlName(buildDaoName(ms.getId()) + "_LIMIT");
		return invocation.proceed();
	} finally {
		DaoContextHolder.clearSqlName();
	}
}
 
Example #17
Source File: PaginationHandler.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private Long executeQueryCount(Executor executor, MappedStatement countMs, Object parameter,
                               BoundSql boundSql, RowBounds rowBounds,
                               ResultHandler resultHandler) throws IllegalAccessException,
        SQLException {
    CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT,
            boundSql);

    String orignSql = boundSql.getSql().replaceAll(";$", "");
    // count sql
    String countSql = PageSqlUtils.getCountSql(orignSql);

    BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql,
            boundSql.getParameterMappings(), parameter);
    // 执行 count 查询
    Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT,
            resultHandler, countKey, countBoundSql);
    Long count = (Long) ((List) countResultList).get(0);
    return count;
}
 
Example #18
Source File: BaseSelectProvider.java    From tk-mybatis with MIT License 5 votes vote down vote up
/**
 * 查询全部结果
 *
 * @param ms
 * @return
 */
public String selectAll(MappedStatement ms) {
    final Class<?> entityClass = getEntityClass(ms);
    //修改返回值类型为实体类型
    setResultType(ms, entityClass);
    StringBuilder sql = new StringBuilder();
    sql.append(SqlHelper.selectAllColumns(entityClass));
    sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass)));
    sql.append(SqlHelper.orderByDefault(entityClass));
    return sql.toString();
}
 
Example #19
Source File: MapperBuilderAssistant.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void setStatementCache(
    boolean isSelect,
    boolean flushCache,
    boolean useCache,
    Cache cache,
    MappedStatement.Builder statementBuilder) {
  flushCache = valueOrDefault(flushCache, !isSelect);
  useCache = valueOrDefault(useCache, isSelect);
  statementBuilder.flushCacheRequired(flushCache);
  statementBuilder.useCache(useCache);
  statementBuilder.cache(cache);
}
 
Example #20
Source File: UpdateByPrimaryKeySelectiveForceProvider.java    From Mapper with MIT License 5 votes vote down vote up
public String updateByPrimaryKeySelectiveForce(MappedStatement ms) {
    Class entityClass = getEntityClass(ms);
    StringBuilder sql = new StringBuilder();
    sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass), "record"));
    sql.append(this.updateSetColumnsForce(entityClass, "record", true, isNotEmpty()));
    sql.append(SqlHelper.wherePKColumns(entityClass, "record", true));

    return sql.toString();
}
 
Example #21
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 5 votes vote down vote up
/**
 * 包装sql后,重置到invocation中
 * @param invocation
 * @param sql
 * @throws SQLException
 */
private void resetSql2Invocation(Invocation invocation, String sql) throws SQLException {
    final Object[] args = invocation.getArgs();
    MappedStatement statement = (MappedStatement) args[0];
    Object parameterObject = args[1];
    BoundSql boundSql = statement.getBoundSql(parameterObject);
    MappedStatement newStatement = newMappedStatement(statement, new BoundSqlSqlSource(boundSql));
    MetaObject msObject =  MetaObject.forObject(newStatement, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),new DefaultReflectorFactory());
    msObject.setValue("sqlSource.boundSql.sql", sql);
    args[0] = newStatement;
}
 
Example #22
Source File: PaginationPlugin.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
private void cpyAndAppendParameters(MappedStatement ms, Pagination pg, BoundSql boundSql, BoundSql newBoundSql){
	// cpy old parameters
	for (ParameterMapping mapping : newBoundSql.getParameterMappings()) {
		String prop = mapping.getProperty();
		if (boundSql.hasAdditionalParameter(prop)) {
			newBoundSql.setAdditionalParameter(prop,
					boundSql.getAdditionalParameter(prop));
		}
	}
	
	// append pagination parameters
	Configuration cf = ms.getConfiguration();
	TypeHandler<?> type =  cf.getTypeHandlerRegistry().getTypeHandler(Integer.class);
	ParameterMapping offsetMapping = new ParameterMapping.Builder(cf,
			OFFSET_PARAMETER, type).build();
	ParameterMapping limitMapping = new ParameterMapping.Builder(cf,
			LIMIT_PARAMETER, type).build();
	
	ParameterMapping[] mappings = new ParameterMapping[]{offsetMapping, limitMapping}; 
	for (Order order : dialect.order()) {
		newBoundSql.getParameterMappings().add(mappings[order.ordinal()]);
	}
	
	newBoundSql.setAdditionalParameter(OFFSET_PARAMETER, pg.getOffset());
	
	// 如果是Oracle,第二个参数需要设置起始位置加Limit得到结束位置
	// 与MySql是不一样
	if(DBMS.ORACLE.name().equals(dbms)){
		newBoundSql.setAdditionalParameter(LIMIT_PARAMETER, pg.getOffset() + pg.getLimit());
	}else{
		newBoundSql.setAdditionalParameter(LIMIT_PARAMETER, pg.getLimit());
	}
}
 
Example #23
Source File: SqlStatementInterceptor.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object returnValue;
    long start = System.currentTimeMillis();
    // 执行 SQL语句
    returnValue = invocation.proceed();
    long end = System.currentTimeMillis();
    // 耗时
    long time = end - start;
    try {
        final Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = null;
        //获取参数,if语句成立,表示sql语句有参数,参数格式是map形式
        if (args.length > 1)
            parameter = invocation.getArgs()[1];
        // 获取到节点的 id,即 sql语句的 id
        String sqlId = ms.getId();
        // BoundSql就是封装 MyBatis最终产生的 sql类
        BoundSql boundSql = ms.getBoundSql(parameter);
        // 获取节点的配置
        Configuration configuration = ms.getConfiguration();
        // 获取到最终的 sql语句
        printSql(configuration, boundSql, sqlId, time);
    } catch (Exception e) {
        logger.error("sql拦截异常:{} ", e.getMessage());
    }
    return returnValue;
}
 
Example #24
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectTwoSetsOfAuthorsProc(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectTwoSetsOfAuthors", new StaticSqlSource(config,"{call selectTwoSetsOfAuthors(?,?)}"), SqlCommandType.SELECT)
      .statementType(StatementType.CALLABLE)
      .parameterMap(new ParameterMap.Builder(
          config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id1", registry.getTypeHandler(int.class)).build());
              add(new ParameterMapping.Builder(config, "id2", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          ResultMap map = new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build());
              add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build());
            }
          }).build();
          add(map);
          add(map);
        }
      }).build();
  return ms;
}
 
Example #25
Source File: AbstractSelectMethodBuilder.java    From jeesuite-libs with Apache License 2.0 5 votes vote down vote up
@Override
void setResultType(Configuration configuration, MappedStatement ms, Class<?> entityClass) {
      List<ResultMap> resultMaps = new ArrayList<ResultMap>();
      resultMaps.add(getResultMap(configuration,entityClass));
      MetaObject metaObject = SystemMetaObject.forObject(ms);
      metaObject.setValue("resultMaps", Collections.unmodifiableList(resultMaps));
}
 
Example #26
Source File: DeleteBatchIds.java    From Roothub with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    SqlMethod deleteBatchByIds = SqlMethod.DELETE_BATCH_BY_IDS;
    String sqlScript = String.format(deleteBatchByIds.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(), getIdsScript());
    SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sqlScript, modelClass);
    return this.addMappedStatement(mapperClass, deleteBatchByIds.getMethod(), sqlSource, SqlCommandType.DELETE, String.class, null, Integer.class, new NoKeyGenerator(), tableInfo.getKeyProperty(), tableInfo.getKeyColumn());
}
 
Example #27
Source File: TableEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    if (sql.contains("#t")) {
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        metaObject.setValue("delegate.boundSql.sql", sql.replace("#t",
                EntityUtils.getTableName(entityType, configuration.getNameAdaptor())));
    }
}
 
Example #28
Source File: SelectPartialMapperProvider.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
public String partialIn(MappedStatement ms) {
	final Class<?> entityClass = getEntityClass(ms);
	String tableName = tableName(entityClass);
	StringBuilder sql = new StringBuilder();
	sql.append("SELECT ");
	sql.append(tableName).append(".${fieldName} ");
	sql.append(SqlHelper.fromTable(entityClass, tableName));
	sql.append(" where ");
	sql.append(tableName).append(".${paramName}");
	sql.append(" in ");
	sql.append("<foreach collection=\"params\" item=\"item\" index=\"index\" open=\"(\" close=\")\" separator=\",\">");
	sql.append(" #{item} ");
	sql.append("</foreach>");
	return sql.toString();
}
 
Example #29
Source File: DataPermissionInterceptor.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
private DataPermission getDataPermission(MappedStatement mappedStatement) {
    String mappedStatementId = mappedStatement.getId();
    DataPermission dataPermission = null;
    try {
        String className = mappedStatementId.substring(0, mappedStatementId.lastIndexOf("."));
        final Class<?> clazz = Class.forName(className);
        if (clazz.isAnnotationPresent(DataPermission.class)) {
            dataPermission = clazz.getAnnotation(DataPermission.class);
        }
    } catch (Exception ignore) {
    }
    return dataPermission;
}
 
Example #30
Source File: SqlServerDialect.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
    String sql = boundSql.getSql();
    String cacheSql = CACHE_COUNTSQL.get(sql);
    if (cacheSql != null) {
        return cacheSql;
    } else {
        cacheSql = sql;
    }
    cacheSql = replaceSql.replace(cacheSql);
    cacheSql = countSqlParser.getSmartCountSql(cacheSql);
    cacheSql = replaceSql.restore(cacheSql);
    CACHE_COUNTSQL.put(sql, cacheSql);
    return cacheSql;
}