Java Code Examples for org.apache.ibatis.session.Configuration#getMappedStatement()

The following examples show how to use org.apache.ibatis.session.Configuration#getMappedStatement() . 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: MultipleCrossIncludeTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void testMappedStatementCache() throws Exception {
  Reader configReader = Resources
  .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MultipleCrossIncludeMapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
  configReader.close();

  Configuration configuration = sqlSessionFactory.getConfiguration();
  configuration.getMappedStatementNames();
  
  MappedStatement selectPetStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePetMapper.select");
  MappedStatement selectPersonStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePersonMapper.select");
  Cache cache = selectPetStatement.getCache();
  assertEquals("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePetMapper", cache.getId());
  assertSame(cache, selectPersonStatement.getCache());
}
 
Example 2
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 3
Source File: XmlExternalRefTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void testMappedStatementCache() throws Exception {
  Reader configReader = Resources
  .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
  configReader.close();

  Configuration configuration = sqlSessionFactory.getConfiguration();
  configuration.getMappedStatementNames();
  
  MappedStatement selectPetStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.PetMapper.select");
  MappedStatement selectPersonStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.PersonMapper.select");
  Cache cache = selectPetStatement.getCache();
  assertEquals("org.apache.ibatis.submitted.xml_external_ref.PetMapper", cache.getId());
  assertSame(cache, selectPersonStatement.getCache());
}
 
Example 4
Source File: MultipleCrossIncludeTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void testMappedStatementCache() throws Exception {
  Reader configReader = Resources
  .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MultipleCrossIncludeMapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
  configReader.close();

  Configuration configuration = sqlSessionFactory.getConfiguration();
  configuration.getMappedStatementNames();
  
  MappedStatement selectPetStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePetMapper.select");
  MappedStatement selectPersonStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePersonMapper.select");
  Cache cache = selectPetStatement.getCache();
  assertEquals("org.apache.ibatis.submitted.xml_external_ref.MultipleCrossIncludePetMapper", cache.getId());
  assertSame(cache, selectPersonStatement.getCache());
}
 
Example 5
Source File: MapperMethod.java    From mybaties 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: XmlExternalRefTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void testMappedStatementCache() throws Exception {
  Reader configReader = Resources
  .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
  configReader.close();

  Configuration configuration = sqlSessionFactory.getConfiguration();
  configuration.getMappedStatementNames();
  
  MappedStatement selectPetStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.PetMapper.select");
  MappedStatement selectPersonStatement = configuration.getMappedStatement("org.apache.ibatis.submitted.xml_external_ref.PersonMapper.select");
  Cache cache = selectPetStatement.getCache();
  assertEquals("org.apache.ibatis.submitted.xml_external_ref.PetMapper", cache.getId());
  assertSame(cache, selectPersonStatement.getCache());
}
 
Example 7
Source File: ShortNameTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void ambiguousShortNameShouldFail() throws Exception {
    Configuration configuration = getConfiguration();
    // ambiguous short name should throw an exception.
    MappedStatement ambiguousStatement = configuration.getMappedStatement("select");
    fail("If there are multiple statements with the same name, an exception should be thrown.");
}
 
Example 8
Source File: NonFullyQualifiedNamespaceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrossReferenceXmlConfig() throws Exception {
    Reader configReader = Resources
            .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespaceConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
    configReader.close();

    Configuration configuration = sqlSessionFactory.getConfiguration();

    MappedStatement selectPerson = configuration.getMappedStatement("person namespace.select");
    assertEquals(
            "org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespacePersonMapper.xml",
            selectPerson.getResource());

    Connection conn = configuration.getEnvironment().getDataSource().getConnection();
    initDb(conn);

    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        Person person = (Person) sqlSession.selectOne("person namespace.select", 1);
        assertEquals((Integer)1, person.getId());
        assertEquals(2, person.getPets().size());
        assertEquals((Integer)2, person.getPets().get(1).getId());

        Pet pet = (Pet) sqlSession.selectOne("person namespace.selectPet", 1);
        assertEquals(Integer.valueOf(1), pet.getId());

        Pet pet2 = (Pet) sqlSession.selectOne("pet namespace.select", 3);
        assertEquals((Integer)3, pet2.getId());
        assertEquals((Integer)2, pet2.getOwner().getId());
    }
    finally {
        sqlSession.close();
    }
}
 
Example 9
Source File: ResultLoaderMap.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public void load(final Object userObject) throws SQLException {
  if (this.metaResultObject == null || this.resultLoader == null) {
    if (this.mappedParameter == null) {
      throw new ExecutorException("Property [" + this.property + "] cannot be loaded because "
              + "required parameter of mapped statement ["
              + this.mappedStatement + "] is not serializable.");
    }

    final Configuration config = this.getConfiguration();
    final MappedStatement ms = config.getMappedStatement(this.mappedStatement);
    if (ms == null) {
      throw new ExecutorException("Cannot lazy load property [" + this.property
              + "] of deserialized object [" + userObject.getClass()
              + "] because configuration does not contain statement ["
              + this.mappedStatement + "]");
    }

    this.metaResultObject = config.newMetaObject(userObject);
    this.resultLoader = new ResultLoader(config, new ClosedExecutor(), ms, this.mappedParameter,
            metaResultObject.getSetterType(this.property), null, null);
  }

  /* We are using a new executor because we may be (and likely are) on a new thread
   * and executors aren't thread safe. (Is this sufficient?)
   *
   * A better approach would be making executors thread safe. */
  if (this.serializationCheck == null) {
    final ResultLoader old = this.resultLoader;
    this.resultLoader = new ResultLoader(old.configuration, new ClosedExecutor(), old.mappedStatement,
            old.parameterObject, old.targetType, old.cacheKey, old.boundSql);
  }

  this.metaResultObject.setValue(property, this.resultLoader.loadResult());
}
 
Example 10
Source File: ShortNameTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void ambiguousShortNameShouldFail() throws Exception {
    Configuration configuration = getConfiguration();
    // ambiguous short name should throw an exception.
    MappedStatement ambiguousStatement = configuration.getMappedStatement("select");
    fail("If there are multiple statements with the same name, an exception should be thrown.");
}
 
Example 11
Source File: ShortNameTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void getStatementByShortName() throws Exception {
    Configuration configuration = getConfiguration();
    // statement can be referenced by its short name.
    MappedStatement selectPet = configuration.getMappedStatement("selectPet");
    assertNotNull(selectPet);
}
 
Example 12
Source File: PaginationHandler.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private MappedStatement extractCountStatementFromConfiguration(final Configuration configuration, final String countStatementId) {
    MappedStatement mappedStatement = null;
    try {
        mappedStatement = configuration.getMappedStatement(countStatementId, false);
    } catch (Throwable t) {
        // NOOP
    }
    return mappedStatement;
}
 
Example 13
Source File: ExecutorUtil.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
/**
 * 尝试获取已经存在的在 MS,提供对手写count和page的支持
 *
 * @param configuration
 * @param msId
 * @return
 */
public static MappedStatement getExistedMappedStatement(Configuration configuration, String msId) {
    MappedStatement mappedStatement = null;
    try {
        mappedStatement = configuration.getMappedStatement(msId, false);
    } catch (Throwable t) {
        //ignore
    }
    return mappedStatement;
}
 
Example 14
Source File: SqlHelper.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 通过命名空间方式获取sql
 * @param session
 * @param namespace
 * @param params
 * @return
 */
public static String getNamespaceSql(SqlSession session, String namespace, Object params) {
    Configuration configuration = session.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
    TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    BoundSql boundSql = mappedStatement.getBoundSql(params);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    String sql = boundSql.getSql();
    if (parameterMappings != null) {
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (params == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
                    value = params;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(params);
                    value = metaObject.getValue(propertyName);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                sql = replaceParameter(sql, value, jdbcType, parameterMapping.getJavaType());
            }
        }
    }
    return sql;
}
 
Example 15
Source File: HierarchicalSqlSessionFactoryBeanTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHierarchyAbstractCollection() throws Exception
{
    Configuration mybatisConfig = getConfiguration(AbstractCollection.class);
    MappedStatement stmt = mybatisConfig.getMappedStatement(QUERY_ABSTRACTCOLLECTION);
    assertNotNull("Query missing for " + QUERY_ABSTRACTCOLLECTION + " using " + AbstractCollection.class, stmt);
    try
    {
        mybatisConfig.getMappedStatement(QUERY_OBJECT);
        fail("Query not missing for " + QUERY_OBJECT + " using " + AbstractCollection.class);
    }
    catch (IllegalArgumentException e)
    {
        // Expected
    }
}
 
Example 16
Source File: HierarchicalSqlSessionFactoryBeanTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHierarchyArrayList() throws Exception
{
    Configuration mybatisConfig = getConfiguration(ArrayList.class);
    MappedStatement stmt = mybatisConfig.getMappedStatement(QUERY_ABSTRACTLIST);
    assertNotNull("Query missing for " + QUERY_ABSTRACTLIST + " using " + ArrayList.class, stmt);
    try
    {
        mybatisConfig.getMappedStatement(QUERY_ABSTRACTCOLLECTION);
        fail("Query not missing for " + QUERY_ABSTRACTCOLLECTION + " using " + ArrayList.class);
    }
    catch (IllegalArgumentException e)
    {
        // Expected
    }
}
 
Example 17
Source File: HierarchicalSqlSessionFactoryBeanTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHierarchyHashSet() throws Exception
{
    Configuration mybatisConfig = getConfiguration(HashSet.class);
    MappedStatement stmt = mybatisConfig.getMappedStatement(QUERY_ABSTRACTCOLLECTION);
    assertNotNull("Query missing for " + QUERY_ABSTRACTCOLLECTION + " using " + HashSet.class, stmt);
    try
    {
        mybatisConfig.getMappedStatement(QUERY_OBJECT);
        fail("Query not missing for " + QUERY_OBJECT + " using " + HashSet.class);
    }
    catch (IllegalArgumentException e)
    {
        // Expected
    }
}
 
Example 18
Source File: HierarchicalSqlSessionFactoryBeanTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testHierarchyTreeSet() throws Exception
{
    Configuration mybatisConfig = getConfiguration(TreeSet.class);
    MappedStatement stmt = mybatisConfig.getMappedStatement(QUERY_TREESET);
    assertNotNull("Query missing for " + QUERY_TREESET + " using " + TreeSet.class, stmt);
    try
    {
        mybatisConfig.getMappedStatement(QUERY_ABSTRACTCOLLECTION);
        fail("Query not missing for " + QUERY_ABSTRACTCOLLECTION + " using " + TreeSet.class);
    }
    catch (IllegalArgumentException e)
    {
        // Expected
    }
}
 
Example 19
Source File: CacheHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
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;
    }
}
 
Example 20
Source File: PaginationHandler.java    From azeroth with Apache License 2.0 4 votes vote down vote up
/**
 * 新建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;
    }

}