org.apache.ibatis.mapping.SqlCommandType Java Examples

The following examples show how to use org.apache.ibatis.mapping.SqlCommandType. 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: BaseDeleteProvider.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * 通过条件删除
 *
 * @param ms
 * @return
 */
public String delete(MappedStatement ms) {
    Class<?> entityClass = getEntityClass(ms);
    StringBuilder sql = new StringBuilder();
    //如果设置了安全删除,就不允许执行不带查询条件的 delete 方法
    if (getConfig().isSafeDelete()) {
        sql.append(SqlHelper.notAllNullParameterCheck("_parameter", EntityHelper.getColumns(entityClass)));
    }
    // 如果是逻辑删除,则修改为更新表,修改逻辑删除字段的值
    if (SqlHelper.hasLogicDeleteColumn(entityClass)) {
        sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
        sql.append("<set>");
        sql.append(SqlHelper.logicDeleteColumnEqualsValue(entityClass, true));
        sql.append("</set>");
        MetaObjectUtil.forObject(ms).setValue("sqlCommandType", SqlCommandType.UPDATE);
    } else {
        sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
    }
    sql.append(SqlHelper.whereAllIfColumns(entityClass, isNotEmpty()));
    return sql.toString();
}
 
Example #2
Source File: RwRouteHandler.java    From jeesuite-libs with Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	//已指定强制使用
	if(MybatisRuntimeContext.isForceUseMaster()){
		logger.debug("Method[{}] force use Master..",ms.getId());
		return null;
	}
	
	//读方法
	if(ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		//!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
		if(!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)){				
			MybatisRuntimeContext.useSlave(true);
			logger.debug("Method[{} use Slave Strategy..",ms.getId());
		}
	}else{
		logger.debug("Method[{}] use Master Strategy..",ms.getId());
		MybatisRuntimeContext.useSlave(false);
	}
	
	return null;
}
 
Example #3
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 6 votes vote down vote up
public static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT)
      .statementType(StatementType.STATEMENT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>()).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(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());
        }
      }).build();
  return ms;
}
 
Example #4
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 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 #5
Source File: MapperMethod.java    From mybatis with Apache License 2.0 6 votes vote down vote up
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
  String statementName = mapperInterface.getName() + "." + method.getName();
  MappedStatement ms = null;
  if (configuration.hasStatement(statementName)) {
    ms = configuration.getMappedStatement(statementName);
  } else if (!mapperInterface.equals(method.getDeclaringClass().getName())) { // issue #35
    //如果不是这个mapper接口的方法,再去查父类
    String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName();
    if (configuration.hasStatement(parentStatementName)) {
      ms = configuration.getMappedStatement(parentStatementName);
    }
  }
  if (ms == null) {
    throw new BindingException("Invalid bound statement (not found): " + statementName);
  }
  name = ms.getId();
  type = ms.getSqlCommandType();
  if (type == SqlCommandType.UNKNOWN) {
    throw new BindingException("Unknown execution method for: " + name);
  }
}
 
Example #6
Source File: MybatisSqlInterceptor.java    From taoshop with Apache License 2.0 6 votes vote down vote up
private String getOperateType(Invocation invocation) {
    final Object[] args = invocation.getArgs();
    MappedStatement ms = (MappedStatement) args[0];
    SqlCommandType commondType = ms.getSqlCommandType();
    if (commondType.compareTo(SqlCommandType.SELECT) == 0) {
        return "select";
    }
    if (commondType.compareTo(SqlCommandType.INSERT) == 0) {
        return "insert";
    }
    if (commondType.compareTo(SqlCommandType.UPDATE) == 0) {
        return "update";
    }
    if (commondType.compareTo(SqlCommandType.DELETE) == 0) {
        return "delete";
    }
    return null;
}
 
Example #7
Source File: MybatisQueryMethod.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
public SqlCommandType getModifyingType() {
	if (!isModifyingQuery()) {
		throw new IllegalStateException(String.format(
				"No annotated @Modifying found for query method %s!", getName()));
	}

	String value = getMergedOrDefaultAnnotationValue("value", Modifying.class,
			String.class);
	if (StringUtils.isEmpty(value)) {
		return null;
	}
	if ("insert".equalsIgnoreCase(value)) {
		return SqlCommandType.INSERT;
	}
	if ("update".equalsIgnoreCase(value)) {
		return SqlCommandType.UPDATE;
	}
	if ("delete".equalsIgnoreCase(value)) {
		return SqlCommandType.DELETE;
	}
	return null;
}
 
Example #8
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT)
      .statementType(StatementType.STATEMENT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>()).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(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());
        }
      }).build();
  return ms;
}
 
Example #9
Source File: UpdateBuilder.java    From azeroth with Apache License 2.0 6 votes vote down vote up
/**
 * @param configuration
 * @param entity
 */
public static void build(Configuration configuration, LanguageDriver languageDriver,
                         EntityInfo entity) {
    String[] names = GeneralSqlGenerator.methodDefines.updateName().split(",");
    for (String name : names) {
        String msId = entity.getMapperClass().getName() + "." + name;

        EntityMapper entityMapper = EntityHelper.getEntityMapper(entity.getEntityClass());

        String sql = buildUpdateSql(entityMapper, name.endsWith("Selective"));

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql,
                entity.getEntityClass());

        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration,
                msId, sqlSource, SqlCommandType.UPDATE);

        MappedStatement statement = statementBuilder.build();

        configuration.addMappedStatement(statement);
    }
}
 
Example #10
Source File: MybatisMapperBuildAssistant.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
protected void addMappedStatement(String id, String[] sqls,
		SqlCommandType sqlCommandType, Class<?> parameterType, String resultMap,
		Class<?> resultType, KeyGenerator keyGenerator, String keyProperty,
		String keyColumn) {

	boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
	boolean flushCache = !isSelect;
	boolean useCache = isSelect;

	addMappedStatement(id, buildSqlSourceFromStrings(sqls, parameterType),
			StatementType.PREPARED, sqlCommandType, null, null, null, parameterType,
			resultMap, resultType, null, flushCache, useCache, false, keyGenerator,
			keyProperty, keyColumn, null, getLanguageDriver(), null);

	if (log.isDebugEnabled()) {
		System.out.println("/*【" + this.assistant.getCurrentNamespace() + '.' + id
				+ "】ResultMap=" + resultMap + " */");
		System.out.println((sqls.length > 1 ? sqls[1] : sqls[0]) + ";\n");
	}
}
 
Example #11
Source File: CheckSQLInterceptor.java    From java-tutorial with MIT License 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

    //获取方法的第0个参数,也就是MappedStatement。@Signature注解中的args中的顺序
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    //获取sql命令操作类型
    SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
    final Object[] queryArgs = invocation.getArgs();
    final Object parameter = queryArgs[1];

    BoundSql boundSql = mappedStatement.getBoundSql(parameter);
    String sql = boundSql.getSql();

    if (SqlCommandType.DELETE.equals(sqlCommandType)) {
        //格式化sql
        sql = sql.replace("\n", "");
        if (!sql.toLowerCase().contains(SQL_DELETE_WHERE)) {
            sql = sql.replace(" ", "");
            logger.warn("删除语句中没有where条件,sql为:{}", sql);
            throw new SQLException("删除语句中没有where条件");
        }
        return invocation.proceed();
    }

    return null;
}
 
Example #12
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 #13
Source File: BaseDeleteProvider.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * 通过主键删除
 *
 * @param ms
 */
public String deleteByPrimaryKey(MappedStatement ms) {
    final Class<?> entityClass = getEntityClass(ms);
    StringBuilder sql = new StringBuilder();
    if (SqlHelper.hasLogicDeleteColumn(entityClass)) {
        sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
        sql.append("<set>");
        sql.append(SqlHelper.logicDeleteColumnEqualsValue(entityClass, true));
        sql.append("</set>");
        MetaObjectUtil.forObject(ms).setValue("sqlCommandType", SqlCommandType.UPDATE);
    } else {
        sql.append(SqlHelper.deleteFromTable(entityClass, tableName(entityClass)));
    }
    sql.append(SqlHelper.wherePKColumns(entityClass));
    return sql.toString();
}
 
Example #14
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareUpdateAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "updateAuthor", new StaticSqlSource(config,"UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), SqlCommandType.UPDATE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .cache(authorCache).build();
  return ms;
}
 
Example #15
Source File: DataPermissionInterceptor.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    this.sqlParser(metaObject);
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    Object paramObj = boundSql.getParameterObject();
    // 数据权限只针对查询语句
    if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
        DataPermission dataPermission = getDataPermission(mappedStatement);
        if (shouldFilter(mappedStatement, dataPermission)) {
            String id = mappedStatement.getId();
            log.info("\n 数据权限过滤 method -> {}", id);
            String originSql = boundSql.getSql();
            String dataPermissionSql = dataPermissionSql(originSql, dataPermission);
            metaObject.setValue("delegate.boundSql.sql", dataPermissionSql);
            log.info("\n originSql -> {} \n dataPermissionSql: {}", originSql, dataPermissionSql);
        }
    }
    return invocation.proceed();
}
 
Example #16
Source File: RwRouteHandler.java    From azeroth with Apache License 2.0 6 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {

    Object[] objects = invocation.getArgs();
    MappedStatement ms = (MappedStatement) objects[0];
    //已指定强制使用
    if (DataSourceContextHolder.get().isForceUseMaster()) {
        logger.debug("Method[{}] force use Master..", ms.getId());
        return null;
    }

    //读方法
    if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
        //!selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
        if (!ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
            DataSourceContextHolder.get().useSlave(true);
            logger.debug("Method[{} use Slave Strategy..", ms.getId());
        }
    } else {
        logger.debug("Method[{}] use Master Strategy..", ms.getId());
        DataSourceContextHolder.get().useSlave(false);
    }

    return null;
}
 
Example #17
Source File: SundialInterceptor.java    From Milkomeda with MIT License 6 votes vote down vote up
private void updateSql(String sql, Invocation invocation, MappedStatement ms, Object[] args, BoundSql boundSql) {
    BoundSql boundSqlNew = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement mappedStatement = copyFrom(ms, new BoundSqlSqlSource(boundSqlNew));
    // 替换映射的语句
    args[0] = mappedStatement;

    // 针对查询方式的参数替换
    if (ms.getSqlCommandType() == SqlCommandType.SELECT) {
        Executor executor = (Executor) invocation.getTarget();
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        // 6个参数时(因为分页插件的原因导致问题,需要修改对应的类型值)
        if (args.length == 6) {
            args[4] = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
            args[5] = boundSqlNew;
        }
    }
}
 
Example #18
Source File: MapperBuilderAssistant.java    From mybaties with Apache License 2.0 5 votes vote down vote up
/** Backward compatibility signature */
//向后兼容方法
public MappedStatement addMappedStatement(
  String id,
  SqlSource sqlSource,
  StatementType statementType,
  SqlCommandType sqlCommandType,
  Integer fetchSize,
  Integer timeout,
  String parameterMap,
  Class<?> parameterType,
  String resultMap,
  Class<?> resultType,
  ResultSetType resultSetType,
  boolean flushCache,
  boolean useCache,
  boolean resultOrdered,
  KeyGenerator keyGenerator,
  String keyProperty,
  String keyColumn,
  String databaseId,
  LanguageDriver lang) {
  return addMappedStatement(
    id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, 
    parameterMap, parameterType, resultMap, resultType, resultSetType, 
    flushCache, useCache, resultOrdered, keyGenerator, keyProperty, 
    keyColumn, databaseId, lang, null);
}
 
Example #19
Source File: InsertBuilder.java    From azeroth with Apache License 2.0 5 votes vote down vote up
/**
 * @param configuration
 * @param entity
 */
public static void build(Configuration configuration, LanguageDriver languageDriver, EntityInfo entity) {

    String[] names = GeneralSqlGenerator.methodDefines.insertName().split(",");
    for (String name : names) {
        String msId = entity.getMapperClass().getName() + "." + name;

        // 从参数对象里提取注解信息
        EntityMapper entityMapper = EntityHelper.getEntityMapper(entity.getEntityClass());
        // 生成sql
        String sql = buildInsertSql(entityMapper, name.endsWith("Selective"));

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, entity.getEntityClass());

        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.INSERT);

        KeyGenerator keyGenerator = entityMapper.autoId() ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
        statementBuilder.keyGenerator(keyGenerator)//
                .keyProperty(entityMapper.getIdColumn().getProperty())//
                .keyColumn(entityMapper.getIdColumn().getColumn());

        MappedStatement statement = statementBuilder.build();

        configuration.addMappedStatement(statement);
    }

}
 
Example #20
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectOneAuthorMappedStatementWithConstructorResults(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, null, "id", registry.getTypeHandler(Integer.class)).javaType(int.class).flags(new ArrayList<ResultFlag>() {
                {
                  add(ResultFlag.CONSTRUCTOR);
                }
              }).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());
              add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build());
            }
          }).build());
        }
      })
      .cache(authorCache)
      .build();
  return ms;
}
 
Example #21
Source File: EntityExecutor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public int update(final MappedStatement ms, final Object parameter) throws SQLException {
  SqlCommandType commandType = ms.getSqlCommandType();
  if (commandType != SELECT && frozen.get()) {
    log.debug("Disallowing {} because the application is frozen", commandType);
    throw new FrozenException(commandType + " is not allowed while the application is frozen");
  }
  if (commandType == INSERT && parameter instanceof HasEntityId) {
    generateEntityId((HasEntityId) parameter);
  }
  return delegate.update(ms, parameter);
}
 
Example #22
Source File: AuditingInterceptor.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {

	MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
	SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
	Object target = invocation.getArgs()[1];
	if (INSERT == sqlCommandType) {
		listener.touchForCreate(target);
	}
	else if (UPDATE == sqlCommandType) {
		listener.touchForUpdate(target);
	}
	return invocation.proceed();
}
 
Example #23
Source File: MybatisMapperBuildAssistant.java    From spring-data-mybatis with Apache License 2.0 5 votes vote down vote up
protected void addMappedStatement(String id, SqlSource sqlSource,
		StatementType statementType, SqlCommandType sqlCommandType, Integer fetchSize,
		Integer timeout, String parameterMap, Class<?> parameterType,
		String resultMap, Class<?> resultType, ResultSetType resultSetType,
		boolean flushCache, boolean useCache, boolean resultOrdered,
		KeyGenerator keyGenerator, String keyProperty, String keyColumn,
		String databaseId, LanguageDriver lang, String resultSets) {

	assistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
			fetchSize, timeout, parameterMap, parameterType, resultMap, resultType,
			resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
			keyProperty, keyColumn, databaseId, lang, resultSets);

}
 
Example #24
Source File: XMLStatementBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> parameterTypeClass, LanguageDriver langDriver, String databaseId) {
  String resultType = nodeToHandle.getStringAttribute("resultType");
  Class<?> resultTypeClass = resolveClass(resultType);
  StatementType statementType = StatementType.valueOf(nodeToHandle.getStringAttribute("statementType", StatementType.PREPARED.toString()));
  String keyProperty = nodeToHandle.getStringAttribute("keyProperty");
  String keyColumn = nodeToHandle.getStringAttribute("keyColumn");
  boolean executeBefore = "BEFORE".equals(nodeToHandle.getStringAttribute("order", "AFTER"));

  //defaults
  boolean useCache = false;
  boolean resultOrdered = false;
  KeyGenerator keyGenerator = new NoKeyGenerator();
  Integer fetchSize = null;
  Integer timeout = null;
  boolean flushCache = false;
  String parameterMap = null;
  String resultMap = null;
  ResultSetType resultSetTypeEnum = null;

  SqlSource sqlSource = langDriver.createSqlSource(configuration, nodeToHandle, parameterTypeClass);
  SqlCommandType sqlCommandType = SqlCommandType.SELECT;

  builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
      fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
      resultSetTypeEnum, flushCache, useCache, resultOrdered,
      keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);

  id = builderAssistant.applyCurrentNamespace(id, false);

  MappedStatement keyStatement = configuration.getMappedStatement(id, false);
  configuration.addKeyGenerator(id, new SelectKeyGenerator(keyStatement, executeBefore));
}
 
Example #25
Source File: DynamicDataSourcePlugin.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
private DynamicDataSourceType getDynamicDataSourceType(final MappedStatement mappedStatement) {
    final DynamicDataSourceType dynamicDataSourceType = cacheMap.get(mappedStatement.getId());
    if (dynamicDataSourceType != null) {
        return dynamicDataSourceType;
    }
    //如是不是select语句则使用主库
    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return DynamicDataSourceType.WRITE;
    }
    //selectKey为自增id查询主键(SELECT LAST_INSERT_ID())方法,使用主库
    if (mappedStatement.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
        return DynamicDataSourceType.WRITE;
    }
    return DynamicDataSourceType.READ;
}
 
Example #26
Source File: XMLStatementBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> parameterTypeClass, LanguageDriver langDriver, String databaseId) {
  String resultType = nodeToHandle.getStringAttribute("resultType");
  Class<?> resultTypeClass = resolveClass(resultType);
  StatementType statementType = StatementType.valueOf(nodeToHandle.getStringAttribute("statementType", StatementType.PREPARED.toString()));
  String keyProperty = nodeToHandle.getStringAttribute("keyProperty");
  String keyColumn = nodeToHandle.getStringAttribute("keyColumn");
  boolean executeBefore = "BEFORE".equals(nodeToHandle.getStringAttribute("order", "AFTER"));

  //defaults
  boolean useCache = false;
  boolean resultOrdered = false;
  KeyGenerator keyGenerator = new NoKeyGenerator();
  Integer fetchSize = null;
  Integer timeout = null;
  boolean flushCache = false;
  String parameterMap = null;
  String resultMap = null;
  ResultSetType resultSetTypeEnum = null;

  SqlSource sqlSource = langDriver.createSqlSource(configuration, nodeToHandle, parameterTypeClass);
  SqlCommandType sqlCommandType = SqlCommandType.SELECT;

  builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
      fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
      resultSetTypeEnum, flushCache, useCache, resultOrdered,
      keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);

  id = builderAssistant.applyCurrentNamespace(id, false);

  MappedStatement keyStatement = configuration.getMappedStatement(id, false);
  configuration.addKeyGenerator(id, new SelectKeyGenerator(keyStatement, executeBefore));
}
 
Example #27
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectOneAuthorMappedStatementWithConstructorResults(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = ?"), SqlCommandType.SELECT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, null, "id", registry.getTypeHandler(Integer.class)).javaType(int.class).flags(new ArrayList<ResultFlag>() {
                {
                  add(ResultFlag.CONSTRUCTOR);
                }
              }).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());
              add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build());
            }
          }).build());
        }
      })
      .cache(authorCache)
      .build();
  return ms;
}
 
Example #28
Source File: ExecutorTestHelper.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareDeleteAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "deleteAuthor", new StaticSqlSource(config,"DELETE FROM author WHERE id = ?"), SqlCommandType.DELETE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .cache(authorCache)
      .build();
  return ms;
}
 
Example #29
Source File: DataScopeInterceptor.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
	MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
	this.sqlParser(metaObject);
	// 先判断是不是SELECT操作
	MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
	if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
		return invocation.proceed();
	}

	BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
	String originalSql = boundSql.getSql();
	Object parameterObject = boundSql.getParameterObject();

	//查找参数中包含DataScope类型的参数
	DataScope dataScope = findDataScopeObject(parameterObject);

	if (dataScope == null) {
		return invocation.proceed();
	} else {
		String scopeName = dataScope.getScopeName();
		List<Integer> deptIds = dataScope.getDeptIds();
		if (StrUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)) {
			String join = CollectionUtil.join(deptIds, ",");
			originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
			metaObject.setValue("delegate.boundSql.sql", originalSql);
		}
		return invocation.proceed();
	}
}
 
Example #30
Source File: ReadOnlyForTestProtectHandler.java    From jeesuite-config with Apache License 2.0 5 votes vote down vote up
@Override
public Object onInterceptor(Invocation invocation) throws Throwable {
	Object[] objects = invocation.getArgs();
	MappedStatement ms = (MappedStatement) objects[0];
	if(!ms.getSqlCommandType().equals(SqlCommandType.SELECT)){
		if(SecurityUtil.getLoginUserInfo().getName().startsWith("test")){
			throw new JeesuiteBaseException(4003, "测试账号已开启敏感操作保护");
		}
	}
	return null;
}