Java Code Examples for org.apache.ibatis.mapping.MappedStatement

The following examples show how to use org.apache.ibatis.mapping.MappedStatement. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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 Project: mybaties   Source File: CachingExecutor.java    License: 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 3
Source Project: mybatis   Source File: SimpleExecutor.java    License: 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 4
Source Project: mybaties   Source File: BaseExecutorTest.java    License: 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 Project: mybatis-jpa   Source File: UpdateStatementFactory.java    License: 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 6
Source Project: Zebra   Source File: PageInterceptor.java    License: 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 7
Source Project: azeroth   Source File: PaginationHandler.java    License: 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 8
Source Project: Milkomeda   Source File: HaloInterceptor.java    License: 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 9
Source Project: mybatis-jpa   Source File: AnnotationStatementScanner.java    License: 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 10
Source Project: mybaties   Source File: BaseExecutorTest.java    License: 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 11
Source Project: joyqueue   Source File: PageResultInterceptor.java    License: 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 Project: mybatis   Source File: BaseExecutorTest.java    License: 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 Project: mybatis   Source File: BaseExecutorTest.java    License: 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 14
Source Project: mybaties   Source File: BaseExecutorTest.java    License: 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 15
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: 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 16
Source Project: easyooo-framework   Source File: PaginationPlugin.java    License: 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 17
Source Project: mybaties   Source File: BatchExecutor.java    License: 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 18
Source Project: mybatis   Source File: ReuseExecutor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Configuration configuration = ms.getConfiguration();
  StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
  Statement stmt = prepareStatement(handler, ms.getStatementLog());
  return handler.<E>query(stmt, resultHandler);
}
 
Example 19
public static boolean isNestedStatement(MappedStatement mappedStatement) {
    SqlRequestContext context = SqlRequestContextHolder.getInstance().get();
    if (Objects.isNull(context)) {
        return false;
    }
    String querySqlId = context.getString(MybatisSqlRequestContextKeys.QUERY_SQL_ID);

    return Objects.isNotNull(querySqlId) && !querySqlId.equals(mappedStatement.getId()) ;
}
 
Example 20
Source Project: jeesuite-libs   Source File: CacheHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void tryRemarkCleanRalationCache(MappedStatement mt){
	String mapperId = mt.getId();
	if(!requiredCheckCacheMethodMapppings.containsKey(mapperId))return;
	List<String> list = requiredCheckCacheMethodMapppings.get(mapperId);
	//
	long score = System.currentTimeMillis() / 1000 - baseScore;
	String contextParam;
	QueryMethodCache metadata;
	for (String queryMapperId : list) {
		metadata = getQueryMethodCache(queryMapperId);
		if(!metadata.checkExpired)continue;
		if(metadata.contextParam != null){
			contextParam = MybatisRuntimeContext.getContextParam(metadata.contextParam);
			if(contextParam == null){
				logger.warn(">>auto_cache_process markCacheExpired contextParamValIsNull ->method:{},queryMethod:{},contextParam:{}",mapperId,queryMapperId,metadata.contextParam);
				return;
			}
		}else{
			contextParam = StringUtils.EMPTY;
		}
		String value = String.format(VALUE_TEMPLATE, contextParam,queryMapperId);
		getCacheProvider().addZsetValue(KEY_NAME, value, score);
		if(metadata.contextParam == null){
			getCacheProvider().remove(value);
		}
		if(logger.isDebugEnabled())logger.debug(">>auto_cache_process markCacheExpired ->method:{}, addKey :{},cleanScore:{}",mapperId,value,score);
	}
}
 
Example 21
Source Project: mybaties   Source File: DefaultSqlSession.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    //根据statement id找到对应的MappedStatement
    MappedStatement ms = configuration.getMappedStatement(statement);
    //转而用执行器来查询结果,注意这里传入的ResultHandler是null
    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}
 
Example 22
Source Project: Roothub   Source File: Insert.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    SqlMethod insert = SqlMethod.INSERT;
    String sqlScript = String.format(insert.getSql(), tableInfo.getTableName(), tableInfo.getInsertColumnSegments(), tableInfo.getInsertValueSegments());
    SqlSource sqlSource = this.languageDriver.createSqlSource(this.configuration, sqlScript, modelClass);
    return this.addMappedStatement(mapperClass, insert.getMethod(), sqlSource, SqlCommandType.INSERT, String.class, null, Integer.class, new NoKeyGenerator(), tableInfo.getKeyProperty(), tableInfo.getKeyColumn());
}
 
Example 23
public CustomMybatisParameterHandler(final MappedStatement mappedStatement, final Object parameterObject, final BoundSql boundSql) {
    this.mappedStatement = mappedStatement;
    this.configuration = mappedStatement.getConfiguration();
    this.typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    this.parameterObject = parameterObject;
    this.boundSql = boundSql;
}
 
Example 24
Source Project: das   Source File: TransController.java    License: Apache License 2.0 5 votes vote down vote up
private Collection<MappedStatement> uniqueStatements(Collection<MappedStatement> mappedStatements) {
    HashMap<String, MappedStatement> map = newLinkedHashMap();
    for(MappedStatement ms : mappedStatements) {
        map.put(ms.getId(), ms);
    }
    return map.values();
}
 
Example 25
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareComplexSelectBlogMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  final SqlSource sqlSource = new StaticSqlSource(config, "SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" +
      " FROM blog b" +
      " INNER JOIN author a ON b.author_id = a.id" +
      " WHERE b.id = ?");
  final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", int.class,
      new ArrayList<ParameterMapping>() {
        {
          add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
        }
      }).build();
  final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, new ArrayList<ResultMapping>() {
    {
      add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class))
          .flags(new ArrayList<ResultFlag>() {
            {
              add(ResultFlag.ID);
            }
          }).build());
      add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)).build());
      add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)).javaType(List.class).nestedQueryId("selectPostsForBlog").build());
    }
  }).build();

  return new MappedStatement.Builder(config, "selectBlogById", sqlSource, SqlCommandType.SELECT)
      .parameterMap(parameterMap)
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(resultMap);
        }
      }).build();
}
 
Example 26
Source Project: Milkomeda   Source File: HaloInterceptor.java    License: MIT License 5 votes vote down vote up
private void invokeWithTable(String tableName, String matchTableName, String sql, MappedStatement mappedStatement, Object param, Object result, HaloType type) {
    if (!HaloContext.getTableNameMap().containsKey(matchTableName)) {
        return;
    }
    HaloContext.getTableNameMap().get(matchTableName).stream()
            .filter(metaData -> metaData.getAttributes().get(HaloContext.ATTR_TYPE) == type)
            .forEach(handlerMetaData -> {
                if ((boolean) handlerMetaData.getAttributes().get(HaloContext.ATTR_ASYNC)) {
                    PulsarHolder.getPulsar().post(() -> invokeHandler(tableName, handlerMetaData, sql, mappedStatement, param, result));
                } else {
                    invokeHandler(tableName, handlerMetaData, sql, mappedStatement, param, result);
                }
            });
}
 
Example 27
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: 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 28
Source Project: FEBS-Cloud   Source File: DataPermissionInterceptor.java    License: 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 29
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 30
Source Project: Mapper   Source File: IdListProvider.java    License: MIT License 5 votes vote down vote up
/**
 * 根据主键字符串进行查询,类中只有存在一个带有@Id注解的字段
 *
 * @param ms
 * @return
 */
public String selectByIdList(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)));
    appendWhereIdList(sql, entityClass, false);
    return sql.toString();
}