Java Code Examples for org.apache.ibatis.mapping.MappedStatement#getId()
The following examples show how to use
org.apache.ibatis.mapping.MappedStatement#getId() .
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: CacheRefreshHelper.java From jeesuite-libs with Apache License 2.0 | 6 votes |
public boolean skipCache(MappedStatement mt){ String userId = MybatisRuntimeContext.getCurrentUserId(); if(userId == null)return false; boolean methodSkip = false; String mapperId = mt.getId(); for (List<String> mtIds : requireCleanCacheMappedStatementIds.values()) { if(methodSkip = mtIds.contains(mapperId))break; } if(methodSkip){ String value = String.format(VALUE_TEMPLATE, userId,mapperId); //Long res = redisTemplate.opsForSet().remove(KEY_NAME, value); Long res = redisTemplate.opsForZSet().remove(KEY_NAME, value); return res > 0; } return false; }
Example 2
Source File: DataPermissionInterceptor.java From FEBS-Cloud with Apache License 2.0 | 6 votes |
@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 3
Source File: CryptInterceptor.java From mybatis-crypt with MIT License | 6 votes |
/** * 获取 方法上的注解 * * @param statement * @return * @throws ClassNotFoundException */ private Boolean getMethodAnnotations(MappedStatement statement) throws ClassNotFoundException { final String id = statement.getId(); Boolean bo = METHOD_ANNOTATIONS_MAP.get(id); if (bo != null) { return bo; } Method m = getMethodByMappedStatementId(id); if (m == null) { return Boolean.FALSE; } final CryptField cryptField = m.getAnnotation(CryptField.class); // 如果允许解密 if (cryptField != null && cryptField.decrypt()) { bo = Boolean.TRUE; } else { bo = Boolean.FALSE; } Boolean bo1 = METHOD_ANNOTATIONS_MAP.putIfAbsent(id, bo); if (bo1 != null) { bo = bo1; } return bo; }
Example 4
Source File: PaginationInterceptor.java From Shop-for-JavaWeb with MIT License | 6 votes |
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null) { for (String keyProperty : ms.getKeyProperties()) { builder.keyProperty(keyProperty); } } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.cache(ms.getCache()); return builder.build(); }
Example 5
Source File: MyBatisUtils.java From platform with Apache License 2.0 | 6 votes |
/** * 复制MappedStatement * * @param ms {@link MappedStatement} * @param newSqlSource {@link SqlSource} * @return {@link MappedStatement} */ public static MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder( ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType() ); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); String[] keyProperties = ms.getKeyProperties(); builder.keyProperty(keyProperties == null ? null : keyProperties[0]); builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); }
Example 6
Source File: MapperTemplate.java From Mapper with MIT License | 6 votes |
/** * 获取返回值类型 - 实体类型 * * @param ms * @return */ public Class<?> getEntityClass(MappedStatement ms) { String msId = ms.getId(); if (entityClassMap.containsKey(msId)) { return entityClassMap.get(msId); } else { Class<?> mapperClass = getMapperClass(msId); Type[] types = mapperClass.getGenericInterfaces(); for (Type type : types) { if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) type; if (t.getRawType() == this.mapperClass || this.mapperClass.isAssignableFrom((Class<?>) t.getRawType())) { Class<?> returnType = (Class<?>) t.getActualTypeArguments()[0]; //获取该类型后,第一次对该类型进行初始化 EntityHelper.initEntityNameMap(returnType, mapperHelper.getConfig()); entityClassMap.put(msId, returnType); return returnType; } } } } throw new MapperException("无法获取 " + msId + " 方法的泛型信息!"); }
Example 7
Source File: MybatisInterceptor.java From DDMQ with Apache License 2.0 | 5 votes |
public Object intercept(Invocation invocation) throws Throwable { Object returnValue; if (showDetailSql || showCostTime) { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = null; if (invocation.getArgs().length > 1) { parameter = invocation.getArgs()[1]; } String sqlId = mappedStatement.getId(); BoundSql boundSql = mappedStatement.getBoundSql(parameter); Configuration configuration = mappedStatement.getConfiguration(); long start = System.currentTimeMillis(); returnValue = invocation.proceed(); long end = System.currentTimeMillis(); long time = (end - start); String sql = getSql(configuration, boundSql, sqlId, time); if (slowSqlMs != 0 && time > slowSqlMs) { log.warn(sql); } else { log.info(sql); } } else { returnValue = invocation.proceed(); } return returnValue; }
Example 8
Source File: IdentityKeyGenerator.java From mybatis-jpa with Apache License 2.0 | 5 votes |
public void processGeneratedKeys(MappedStatement ms, Statement stmt, Object parameter) { final String[] keyProperties = ms.getKeyProperties(); if (keyProperties == null || keyProperties.length == 0) { return; } if (keyProperties.length > 1) { throw new ExecutorException( "There are more than one keyProperty in MappedStatement : " + ms.getId() + "."); } if (parameter instanceof Collection) { handleCollection(ms, stmt, (Collection) parameter); } else if (parameter.getClass().isArray()) { handleCollection(ms, stmt, Arrays.asList(parameter)); } else if (parameter instanceof Map) { Map parameterMap = (Map) parameter; if (parameterMap.containsKey("collection")) { handleCollection(ms, stmt, (Collection) parameterMap.get("collection")); } else if (parameterMap.containsKey("list")) { handleCollection(ms, stmt, (List) parameterMap.get("list")); } else if (parameterMap.containsKey("array")) { handleCollection(ms, stmt, Arrays.asList((Object[]) parameterMap.get("array"))); } } else { handleObject(ms, stmt, parameter, idGenerator.nextId()); } }
Example 9
Source File: MyBatisUtils.java From platform with Apache License 2.0 | 5 votes |
/** * 获取方法返回类型 * * @param mappedStatement {@link MappedStatement} * @return Class */ public static Class<?> getReturnType(MappedStatement mappedStatement) { try { String id = mappedStatement.getId(); Class<?> mapperInterface = Class.forName(id.substring(0, id.lastIndexOf("."))); String methodName = id.substring(id.lastIndexOf(".") + 1); Method method = BeanUtils.findMethod(mapperInterface, methodName); return method.getReturnType(); } catch (Exception e) { throw new RuntimeException(e); } }
Example 10
Source File: CachingExecutor.java From mybatis with Apache License 2.0 | 5 votes |
private void ensureNoOutParams(MappedStatement ms, Object parameter, BoundSql boundSql) { if (ms.getStatementType() == StatementType.CALLABLE) { for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) { if (parameterMapping.getMode() != ParameterMode.IN) { throw new ExecutorException("Caching stored procedures with OUT params is not supported. Please configure useCache=false in " + ms.getId() + " statement."); } } } }
Example 11
Source File: CryptInterceptor.java From mybatis-crypt with MIT License | 5 votes |
/** * 获取 方法参数上的注解 * * @param statement * @return * @throws ClassNotFoundException */ private Set<String> getParameterAnnotations(MappedStatement statement) throws ClassNotFoundException { final String id = statement.getId(); Set<String> set = METHOD_PARAM_ANNOTATIONS_MAP.get(id); if (set != null) { return set; } set = new HashSet<>(); Method m = getMethodByMappedStatementId(id); if (m == null) { return set; } final Annotation[][] paramAnnotations = m.getParameterAnnotations(); // get names from @CryptField annotations for (Annotation[] paramAnnotation : paramAnnotations) { for (Annotation annotation : paramAnnotation) { if (annotation instanceof CryptField) { CryptField cryptField = (CryptField) annotation; // 如果允许加密 if (cryptField.encrypt()) { set.add(cryptField.value()); } break; } } } Set<String> oldSet = METHOD_PARAM_ANNOTATIONS_MAP.putIfAbsent(id, set); if (oldSet != null) { set = oldSet; } return set; }
Example 12
Source File: DataPermissionInterceptor.java From DataPermissionHelper with Apache License 2.0 | 5 votes |
@Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement mappedStatement = (MappedStatement) args[0]; Object parameter = args[1]; //从当前线程获取需要进行数据权限控制的业务 DataPermission dataPermission = DPHelper.getLocalDataPermissions(); //判断有没有进行数据权限控制,是不是最高权限的管理员(这里指的是数据权限的白名单用户) if (dataPermission != null && dataPermission.getAdmin() == false) { BoundSql boundSql = mappedStatement.getBoundSql(parameter); String sql = boundSql.getSql(); //获得方法类型 Select select = (Select) CCJSqlParserUtil.parse(sql); select.getSelectBody().accept(new SelectVisitorImpl()); //判断当前sql是否被修改 if (DPHelper.getChangeTable()) { //访问各个visitor //TODO:解析动态sql会失败 BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), select.toString(), boundSql .getParameterMappings(), parameter); String newMsId = mappedStatement.getId() + DATA_PERMISSION; MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql), newMsId); args[0] = newMs; DPHelper.clearChangeTable(); } } return invocation.proceed(); }
Example 13
Source File: SQLHelper.java From Shop-for-JavaWeb with MIT License | 5 votes |
/** * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler * * @param ps 表示预编译的 SQL 语句的对象。 * @param mappedStatement MappedStatement * @param boundSql SQL * @param parameterObject 参数对象 * @throws java.sql.SQLException 数据库异常 */ @SuppressWarnings("unchecked") public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException { ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { Configuration configuration = mappedStatement.getConfiguration(); TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject); for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; String propertyName = parameterMapping.getProperty(); PropertyTokenizer prop = new PropertyTokenizer(propertyName); if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) { value = boundSql.getAdditionalParameter(prop.getName()); if (value != null) { value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length())); } } else { value = metaObject == null ? null : metaObject.getValue(propertyName); } @SuppressWarnings("rawtypes") TypeHandler typeHandler = parameterMapping.getTypeHandler(); if (typeHandler == null) { throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId()); } typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType()); } } } }
Example 14
Source File: OffsetLimitInterceptor.java From AsuraFramework with Apache License 2.0 | 5 votes |
private MappedStatement copyFromMappedStatement(MappedStatement ms,SqlSource newSqlSource) { Builder builder = new Builder(ms.getConfiguration(),ms.getId(),newSqlSource,ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if(ms.getKeyProperties() != null && ms.getKeyProperties().length !=0){ StringBuffer keyProperties = new StringBuffer(); for(String keyProperty : ms.getKeyProperties()){ keyProperties.append(keyProperty).append(","); } keyProperties.delete(keyProperties.length()-1, keyProperties.length()); builder.keyProperty(keyProperties.toString()); } //setStatementTimeout() builder.timeout(ms.getTimeout()); //setStatementResultMap() builder.parameterMap(ms.getParameterMap()); //setStatementResultMap() builder.resultMaps(ms.getResultMaps()); builder.resultSetType(ms.getResultSetType()); //setStatementCache() builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); return builder.build(); }
Example 15
Source File: MybatisProfilerPlugin.java From pepper-metrics with Apache License 2.0 | 5 votes |
@Override public Object intercept(Invocation invocation) throws Throwable { if (!System.getProperty("mybatisProfileEnable", "true").equalsIgnoreCase("true")) { return invocation.proceed(); } final Object[] args = invocation.getArgs(); if (args != null && args.length > 0) { long begin = System.nanoTime(); final MappedStatement mappedStatement = (MappedStatement) args[0]; if (mappedStatement != null) { final String methodName = mappedStatement.getId(); final String declaringTypeName = mappedStatement.getResource(); String[] tags = new String[]{"operation", methodName, "class", declaringTypeName}; try { MYBATIS_STAT.incConc(tags); return invocation.proceed(); } catch (Throwable throwable) { MYBATIS_STAT.error(tags); throw throwable; } finally { MYBATIS_STAT.decConc(tags); MYBATIS_STAT.observe(System.nanoTime() - begin, TimeUnit.NANOSECONDS, tags); } } } return invocation.proceed(); }
Example 16
Source File: MybatisInterceptor.java From DDMQ with Apache License 2.0 | 5 votes |
public Object intercept(Invocation invocation) throws Throwable { Object returnValue; if (showDetailSql || showCostTime) { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = null; if (invocation.getArgs().length > 1) { parameter = invocation.getArgs()[1]; } String sqlId = mappedStatement.getId(); BoundSql boundSql = mappedStatement.getBoundSql(parameter); Configuration configuration = mappedStatement.getConfiguration(); long start = System.currentTimeMillis(); returnValue = invocation.proceed(); long end = System.currentTimeMillis(); long time = (end - start); String sql = getSql(configuration, boundSql, sqlId, time); if (slowSqlMs != 0 && time > slowSqlMs) { log.warn(sql); } else { log.info(sql); } } else { returnValue = invocation.proceed(); } return returnValue; }
Example 17
Source File: DataPermissionInterceptor.java From FEBS-Cloud with Apache License 2.0 | 5 votes |
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 18
Source File: PageStatementInterceptor.java From joyqueue with Apache License 2.0 | 4 votes |
@Override public Object intercept(Invocation invocation) throws Throwable { StatementHandler handler = (StatementHandler) invocation.getTarget(); // 获取MappedStatement,Configuration对象 MetaObject metaObject = MetaObject.forObject(handler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory()); MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement"); String statement = mappedStatement.getId(); if (!isPageSql(statement,metaObject.getValue("boundSql.parameterObject"))) { return invocation.proceed(); } Configuration configuration = (Configuration) metaObject.getValue("delegate.configuration"); Executor executor = (Executor) metaObject.getValue("delegate.executor"); // 获取分页参数 BoundSql boundSql = handler.getBoundSql(); QPageQuery pageQuery = (QPageQuery) boundSql.getParameterObject(); String countStatement = buildCountStatement(statement); List<Integer> counts = executor.query(configuration. getMappedStatement(countStatement), pageQuery, RowBounds.DEFAULT, null); int count = 0; if (counts != null && !counts.isEmpty()) { count = counts.get(0) == null ? 0 : counts.get(0); } if (pageQuery.getPagination() == null) { pageQuery.setPagination(new Pagination()); } pageQuery.getPagination().setTotalRecord(count); String sql = boundSql.getSql(); if (logger.isDebugEnabled()) { logger.debug("raw SQL : " + sql); } if (sql == null || sql.isEmpty() || sql.contains(" limit ")) { return invocation.proceed(); } String originalSql = (String) metaObject.getValue("delegate.boundSql.sql"); metaObject.setValue("delegate.boundSql.sql", getLimitString(originalSql, pageQuery.getPagination().getStart(), pageQuery.getPagination().getSize())); metaObject.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET); metaObject.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT); if (logger.isDebugEnabled()) { logger.debug("pagination SQL : " + sql); } return invocation.proceed(); }
Example 19
Source File: PaginationHandler.java From azeroth with Apache License 2.0 | 4 votes |
/** * 新建count查询的MappedStatement * * @param ms * @return */ public MappedStatement getCountMappedStatement(MappedStatement ms) { String newMsId = ms.getId() + PAGE_COUNT_SUFFIX; MappedStatement statement = null; Configuration configuration = ms.getConfiguration(); try { statement = configuration.getMappedStatement(newMsId); if (statement != null) { return statement; } } catch (Exception e) { } synchronized (configuration) { if (configuration.hasStatement(newMsId)) { return configuration.getMappedStatement(newMsId); } MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, ms.getSqlSource(), ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) { StringBuilder keyProperties = new StringBuilder(); for (String keyProperty : ms.getKeyProperties()) { keyProperties.append(keyProperty).append(","); } keyProperties.delete(keyProperties.length() - 1, keyProperties.length()); builder.keyProperty(keyProperties.toString()); } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); //count查询返回值int List<ResultMap> resultMaps = new ArrayList<ResultMap>(); String id = newMsId + "-Inline"; ResultMap resultMap = new ResultMap.Builder(configuration, id, Long.class, new ArrayList<ResultMapping>(0)).build(); resultMaps.add(resultMap); builder.resultMaps(resultMaps); builder.resultSetType(ms.getResultSetType()); builder.cache(ms.getCache()); builder.flushCacheRequired(ms.isFlushCacheRequired()); builder.useCache(ms.isUseCache()); statement = builder.build(); configuration.addMappedStatement(statement); return statement; } }
Example 20
Source File: CacheHandler.java From azeroth with Apache License 2.0 | 4 votes |
private MappedStatement getQueryIdsMappedStatementForUpdateCache(MappedStatement mt, EntityInfo entityInfo) { String msId = mt.getId() + QUERY_IDS_SUFFIX; MappedStatement statement = null; Configuration configuration = mt.getConfiguration(); try { statement = configuration.getMappedStatement(msId); if (statement != null) { return statement; } } catch (Exception e) { } synchronized (configuration) { if (configuration.hasStatement(msId)) { return configuration.getMappedStatement(msId); } String sql = entityInfo.getMapperSqls().get(mt.getId()); if (StringUtils.isNotBlank(sql)) { if (!sql.toLowerCase().contains(entityInfo.getTableName().toLowerCase())) { return null; } sql = "select " + entityInfo.getIdColumn() + " from " + entityInfo.getTableName() + " WHERE " + sql.split(WHERE_REGEX)[1]; sql = String.format(SqlTemplate.SCRIPT_TEMAPLATE, sql); } else { sql = PARSE_SQL_ERROR_DEFAULT; } SqlSource sqlSource = configuration.getDefaultScriptingLanguageInstance() .createSqlSource(configuration, sql, Object.class); MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.SELECT); statementBuilder.resource(mt.getResource()); statementBuilder.fetchSize(mt.getFetchSize()); statementBuilder.statementType(mt.getStatementType()); statementBuilder.parameterMap(mt.getParameterMap()); statement = statementBuilder.build(); List<ResultMap> resultMaps = new ArrayList<ResultMap>(); String id = msId + "-Inline"; ResultMap.Builder builder = new ResultMap.Builder(configuration, id, entityInfo.getIdType(), new ArrayList<ResultMapping>(), true); resultMaps.add(builder.build()); MetaObject metaObject = SystemMetaObject.forObject(statement); metaObject.setValue("resultMaps", Collections.unmodifiableList(resultMaps)); configuration.addMappedStatement(statement); return statement; } }