org.apache.ibatis.session.Configuration Java Examples

The following examples show how to use org.apache.ibatis.session.Configuration. 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: ExecutorTestHelper.java    From mybatis 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 #2
Source File: BatchExecutor.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example #3
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 #4
Source File: MapperScanApplication.java    From mumu with Apache License 2.0 6 votes vote down vote up
public void init() throws IOException, SAXException, ParserConfigurationException, ClassNotFoundException {
	log.info("parse " + configLocation);
	// 解析xml
	InputStream inputStream=MapperScanApplication.class.getClassLoader().getResourceAsStream(configLocation);
	
	Configuration configuration = sqlSessionFactory.getConfiguration();

	if(inputStream==null){
		return;
	}
	XPathParser xPathParser = new XPathParser(inputStream);
	XNode root = xPathParser.evalNode("/configuration");

	handleSetting(configuration, root);

	handleTypeAlias(configuration, root);

	handleMappers(configuration, root);
}
 
Example #5
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 #6
Source File: MapperHelper.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * 配置指定的接口
 *
 * @param configuration
 * @param mapperInterface
 */
public void processConfiguration(Configuration configuration, Class<?> mapperInterface) {
    String prefix;
    if (mapperInterface != null) {
        prefix = mapperInterface.getCanonicalName();
    } else {
        prefix = "";
    }
    for (Object object : new ArrayList<Object>(configuration.getMappedStatements())) {
        if (object instanceof MappedStatement) {
            MappedStatement ms = (MappedStatement) object;
            if (ms.getId().startsWith(prefix)) {
                processMappedStatement(ms);
            }
        }
    }
}
 
Example #7
Source File: SimpleExecutor.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
  Statement stmt = null;
  try {
    Configuration configuration = ms.getConfiguration();
    //新建一个StatementHandler
    //这里看到ResultHandler传入了
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    //准备语句
    stmt = prepareStatement(handler, ms.getStatementLog());
    //StatementHandler.query
    return handler.<E>query(stmt, resultHandler);
  } finally {
    closeStatement(stmt);
  }
}
 
Example #8
Source File: MapperFactoryBean.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void checkDaoConfig() {
    super.checkDaoConfig();

    notNull(this.mapperInterface, "Property 'mapperInterface' is required");

    Configuration configuration = getSqlSession().getConfiguration();
    if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
        try {
            configuration.addMapper(this.mapperInterface);
        } catch (Exception e) {
            logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
            throw new IllegalArgumentException(e);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    //直接针对接口处理通用接口方法对应的 MappedStatement 是安全的,通用方法不会出现 IncompleteElementException 的情况
    if (configuration.hasMapper(this.mapperInterface) && mapperHelper != null && mapperHelper.isExtendCommonMapper(this.mapperInterface)) {
        mapperHelper.processConfiguration(getSqlSession().getConfiguration(), this.mapperInterface);
    }
}
 
Example #9
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIterateOnceForEachItemInCollection() throws Exception {
  final HashMap<String, String[]> parameterObject = new HashMap<String, String[]>() {{
    put("array", new String[]{"one", "two", "three"});
  }};
  final String expected = "SELECT * FROM BLOG WHERE ID in (  one = ? AND two = ? AND three = ? )";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG WHERE ID in"),
      new ForEachSqlNode(new Configuration(),mixedContents(new TextSqlNode("${item} = #{item}")), "array", "index", "item", "(", ")", "AND"));
  BoundSql boundSql = source.getBoundSql(parameterObject);
  assertEquals(expected, boundSql.getSql());
  assertEquals(3, boundSql.getParameterMappings().size());
  assertEquals("__frch_item_0", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_item_1", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_item_2", boundSql.getParameterMappings().get(2).getProperty());
}
 
Example #10
Source File: MapperAnnotationBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public MapperAnnotationBuilder(Configuration configuration, Class<?> type) {
  String resource = type.getName().replace('.', '/') + ".java (best guess)";
  this.assistant = new MapperBuilderAssistant(configuration, resource);
  this.configuration = configuration;
  this.type = type;

  sqlAnnotationTypes.add(Select.class);
  sqlAnnotationTypes.add(Insert.class);
  sqlAnnotationTypes.add(Update.class);
  sqlAnnotationTypes.add(Delete.class);

  sqlProviderAnnotationTypes.add(SelectProvider.class);
  sqlProviderAnnotationTypes.add(InsertProvider.class);
  sqlProviderAnnotationTypes.add(UpdateProvider.class);
  sqlProviderAnnotationTypes.add(DeleteProvider.class);
}
 
Example #11
Source File: XMLLanguageDriver.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Override
public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
  // issue #3
  if (script.startsWith("<script>")) {
    XPathParser parser = new XPathParser(script, false, configuration.getVariables(), new XMLMapperEntityResolver());
    return createSqlSource(configuration, parser.evalNode("/script"), parameterType);
  } else {
    // issue #127
    script = PropertyParser.parse(script, configuration.getVariables());
    TextSqlNode textSqlNode = new TextSqlNode(script);
    //一种是动态,一种是原始
    if (textSqlNode.isDynamic()) {
      return new DynamicSqlSource(configuration, textSqlNode);
    } else {
      return new RawSqlSource(configuration, script, parameterType);
    }
  }
}
 
Example #12
Source File: MybatisHelper.java    From snakerflow with Apache License 2.0 6 votes vote down vote up
/**
 * 使用DataSource初始化SqlSessionFactory
 * @param ds 数据源
 */
public static void initialize(DataSource ds) {
	TransactionFactory transactionFactory = new MybatisTransactionFactory();
	Environment environment = new Environment("snaker", transactionFactory, ds);
	Configuration configuration = new Configuration(environment);
       configuration.getTypeAliasRegistry().registerAliases(SCAN_PACKAGE, Object.class);
       if (log.isInfoEnabled()) {
       	Map<String, Class<?>> typeAliases = configuration.getTypeAliasRegistry().getTypeAliases();
       	for(Entry<String, Class<?>> entry : typeAliases.entrySet()) {
           	log.info("Scanned class:[name=" + entry.getKey() + ",class=" + entry.getValue().getName() + "]");
       	}
       }
	try {
		for(String resource : resources) {
			InputStream in = Resources.getResourceAsStream(resource);
			XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, resource, configuration.getSqlFragments());
			xmlMapperBuilder.parse();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		ErrorContext.instance().reset();
	}
	sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
 
Example #13
Source File: DmnEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
  XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
  Configuration configuration = parser.getConfiguration();

  if (databaseType != null) {
    configuration.setDatabaseId(databaseType);
  }

  configuration.setEnvironment(environment);

  initCustomMybatisMappers(configuration);

  configuration = parseMybatisConfiguration(configuration, parser);
  return configuration;
}
 
Example #14
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectOneAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();

  final ResultMap rm = 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());
          add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build());
        }
      }).build();

  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(rm);
        }
      })
      .cache(authorCache).build();
  return ms;
}
 
Example #15
Source File: MultipleReverseIncludeTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception {
  Class.forName("org.hsqldb.jdbcDriver");
  Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", "");
  initDb(c);

  Configuration configuration = new Configuration();
  Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource(
      "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null));
  configuration.setEnvironment(environment);

  configuration.addMapper(MultipleReverseIncludePersonMapper.class);

  return new SqlSessionFactoryBuilder().build(configuration);
}
 
Example #16
Source File: FormEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void initCustomMybatisMappers(Configuration configuration) {
  if (getCustomMybatisMappers() != null) {
    for (Class<?> clazz : getCustomMybatisMappers()) {
      configuration.addMapper(clazz);
    }
  }
}
 
Example #17
Source File: ExecutorTestHelper.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectAllAuthorsAutoMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  return new MappedStatement.Builder(config, "selectAuthorAutoMap", new StaticSqlSource(config,"SELECT * FROM author ORDER BY id"), SqlCommandType.SELECT)
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, "favouriteSection", "favourite_section", registry.getTypeHandler(Section.class)).build());
              add(new ResultMapping.Builder(config, null, "not_exists", Object.class).build());
            }
          }).build());
        }
      }).build();
}
 
Example #18
Source File: BlogMain.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void selectHandler(SqlSession session, Configuration configuration) {
	BlogMapper mapper = session.getMapper(BlogMapper.class);
	// DefaultResultHandler内置结果处理器
	DefaultResultHandler defaultHandler = new DefaultResultHandler();
	// System.out.println(mapper.selectBlogsByHandler("zhaohui",
	// defaultHandler));
	System.out.println(defaultHandler.getResultList());

	// DefaultMapResultHandler内置结果处理器
	DefaultMapResultHandler<Long, Blog> defaultMapResultHandler = new DefaultMapResultHandler<Long, Blog>("id",
			configuration.getObjectFactory(), configuration.getObjectWrapperFactory(),
			configuration.getReflectorFactory());
	mapper.selectBlogsByHandler("zhaohui", defaultMapResultHandler);
	System.out.println(defaultMapResultHandler.getMappedResults());
}
 
Example #19
Source File: SqlSessionMapperHotspotLoader.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Clear set cache in configuration.
 * 
 * @param classConfig
 * @param configuration
 * @param fieldName
 * @param clearKey
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
private synchronized void clearSet(Class<?> classConfig, Configuration configuration, String fieldName, Object clearKey)
		throws Exception {
	Field field = classConfig.getDeclaredField(fieldName);
	field.setAccessible(true);
	Set setConfig = (Set) field.get(configuration);
	// (此用于实现只重新加载单个mapper文件的热部署, 但是目前由于未找到清空被修改文件的缓存的key值,
	// 暂无法实现单个mapper热部署)
	// setConfig.remove(clearKey);
	setConfig.clear();
}
 
Example #20
Source File: SqlHelperTkMapperAutoConfiguration.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void customize(Configuration configuration) {
    logger.info("Start to customize mybatis configuration with mybatis-spring-boot-autoconfigure");
    configuration.setDefaultScriptingLanguage(CustomScriptLanguageDriver.class);

    SqlHelperMybatisPlugin plugin = new SqlHelperMybatisPlugin();
    plugin.setPaginationConfig(sqlHelperMybatisProperties.getPagination());
    plugin.setInstrumentorConfig(sqlHelperMybatisProperties.getInstrumentor());
    plugin.init();

    logger.info("Add interceptor {} to mybatis configuration", plugin);
    logger.info("The properties of the mybatis plugin [{}] is: {}", Reflects.getFQNClassName(SqlHelperMybatisPlugin.class), sqlHelperMybatisProperties);
    configuration.addInterceptor(plugin);
}
 
Example #21
Source File: MultipleIncludeTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception {
  Class.forName("org.hsqldb.jdbcDriver");
  Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", "");
  initDb(c);

  Configuration configuration = new Configuration();
  Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource(
      "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null));
  configuration.setEnvironment(environment);

  configuration.addMapper(MultipleIncludePersonMapper.class);

  return new SqlSessionFactoryBuilder().build(configuration);
}
 
Example #22
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREORWithCRLFForFirstCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE \r\n ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   or\r\n ID = ?  ")), "true"
              )
          )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example #23
Source File: SqlLogInterceptor.java    From paascloud-master with Apache License 2.0 5 votes vote down vote up
/**
 * Intercept object.
 *
 * @param invocation the invocation
 *
 * @return the object
 *
 * @throws Throwable the throwable
 */
@Override
public Object intercept(Invocation invocation) throws Throwable {
	long start = System.currentTimeMillis();

	MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
	Object parameter = null;
	if (invocation.getArgs().length > 1) {
		parameter = invocation.getArgs()[1];
	}
	BoundSql boundSql = mappedStatement.getBoundSql(parameter);
	Configuration configuration = mappedStatement.getConfiguration();
	String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
	List<String> paramList = getParamList(configuration, boundSql);
	Object proceed = invocation.proceed();
	int result = 0;
	if (proceed instanceof ArrayList) {
		ArrayList resultList = (ArrayList) proceed;
		result = resultList.size();
	}
	if (proceed instanceof Integer) {
		result = (Integer) proceed;
	}
	if (enableSqlLogInterceptor) {
		long end = System.currentTimeMillis();
		long time = end - start;
		Boolean flag = (Boolean) ThreadLocalMap.get(NotDisplaySqlAspect.DISPLAY_SQL);
		if (time >= noticeTime * GlobalConstant.Number.THOUSAND_INT) {
			log.error("执行超过{}秒,sql={}", noticeTime, sql);
			log.error("result={}, time={}ms, params={}", result, time, paramList);
			return proceed;
		}
		if (flag == null || Objects.equals(flag, true)) {
			log.info("sql={}", sql);
			log.info("result={},time={}ms, params={}", result, time, paramList);
		}
	}
	return proceed;
}
 
Example #24
Source File: ResultMapExtendsTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private SqlSessionFactory getSqlSessionFactoryJavaConfig() throws Exception {
  Class.forName("org.hsqldb.jdbcDriver");
  Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:xmlextref", "sa", "");
  initDb(c);

  Configuration configuration = new Configuration();
  Environment environment = new Environment("development", new JdbcTransactionFactory(), new UnpooledDataSource(
      "org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:xmlextref", null));
  configuration.setEnvironment(environment);

  configuration.addMapper(ResultMapReferencePersonMapper.class);
  configuration.addMapper(ResultMapReferencePetMapper.class);

  return new SqlSessionFactoryBuilder().build(configuration);
}
 
Example #25
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimNoSetClause() throws Exception {
  final String expected = "UPDATE BLOG";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("UPDATE BLOG"),
      new SetSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   , ID = ?   ")), "false"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode(", NAME = ?  ")), "false"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example #26
Source File: ColumnTypeTest.java    From Mapper with MIT License 5 votes vote down vote up
@Before
public void beforeTest(){
    config = new Config();
    config.setStyle(Style.normal);

    configuration = new Configuration();
}
 
Example #27
Source File: BoundSql.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
  this.sql = sql;
  this.parameterMappings = parameterMappings;
  this.parameterObject = parameterObject;
  this.additionalParameters = new HashMap<String, Object>();
  this.metaParameters = configuration.newMetaObject(additionalParameters);
}
 
Example #28
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREInsteadOfANDForFirstCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE  ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and ID = ?  ")), "true"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode("   or NAME = ?  ")), "false"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example #29
Source File: NonFullyQualifiedNamespaceTest.java    From mybaties 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 #30
Source File: XmlExternalRefTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected = BuilderException.class)
public void testFailFastOnBuildAllWithInsert() throws Exception {
  Configuration configuration = new Configuration();
  try {
    configuration.addMapper(InvalidWithInsertMapper.class);
    configuration.addMapper(InvalidMapper.class);
  } catch (Exception e) {
    fail("No exception should be thrown before parsing statement nodes.");
  }
  configuration.getMappedStatementNames();
}