Java Code Examples for org.apache.ibatis.session.Configuration

The following examples show how to use org.apache.ibatis.session.Configuration. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mybatis   Source File: SimpleExecutor.java    License: 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 2
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: 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 3
Source Project: mybaties   Source File: MapperAnnotationBuilder.java    License: 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 4
Source Project: mybaties   Source File: XMLLanguageDriver.java    License: 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 5
Source Project: Mapper   Source File: MapperHelper.java    License: 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 6
Source Project: mumu   Source File: MapperScanApplication.java    License: 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 7
Source Project: Mapper   Source File: MapperFactoryBean.java    License: 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 8
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: 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 9
Source Project: snakerflow   Source File: MybatisHelper.java    License: 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 10
Source Project: mybatis   Source File: XmlExternalRefTest.java    License: 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 11
Source Project: mybatis   Source File: MultipleCrossIncludeTest.java    License: 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 12
Source Project: mybatis   Source File: BatchExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
  final Configuration configuration = ms.getConfiguration();
  final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
  final BoundSql boundSql = handler.getBoundSql();
  final String sql = boundSql.getSql();
  final Statement stmt;
  if (sql.equals(currentSql) && ms.equals(currentStatement)) {
    int last = statementList.size() - 1;
    stmt = statementList.get(last);
    BatchResult batchResult = batchResultList.get(last);
    batchResult.addParameterObject(parameterObject);
  } else {
    Connection connection = getConnection(ms.getStatementLog());
    stmt = handler.prepare(connection);
    currentSql = sql;
    currentStatement = ms;
    statementList.add(stmt);
    batchResultList.add(new BatchResult(ms, sql, parameterObject));
  }
  handler.parameterize(stmt);
  handler.batch(stmt);
  return BATCH_UPDATE_RETURN_VALUE;
}
 
Example 13
@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 14
public static BoundSql rebuildBoundSql(String newSql, Configuration configuration, BoundSql boundSql) {
    BoundSql newBoundSql = new BoundSql(configuration, newSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    final Map<String, Object> additionalParameters = BoundSqls.getAdditionalParameter(boundSql);
    for (Map.Entry<String, Object> entry : additionalParameters.entrySet()) {
        newBoundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
    }
    return newBoundSql;
}
 
Example 15
Source Project: nexus-public   Source File: MyBatisDataStore.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prepare the {@link TypeHandler} for use with this datastore.
 */
private TypeHandlerRegistry prepare(final TypeHandler<?> handler) {
  if (handler instanceof CipherAwareTypeHandler<?>) {
    ((CipherAwareTypeHandler<?>) handler).setCipher(databaseCipher);
  }
  if (sensitiveAttributeFilter != null && handler instanceof AbstractJsonTypeHandler<?>) {
    ((AbstractJsonTypeHandler<?>) handler).encryptSensitiveFields(passwordHelper, sensitiveAttributeFilter);
  }
  Configuration mybatisConfig = sessionFactory.getConfiguration();
  registerSimpleAlias(mybatisConfig.getTypeAliasRegistry(), handler.getClass());
  return mybatisConfig.getTypeHandlerRegistry();
}
 
Example 16
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREInsteadOfORForSecondCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE  NAME = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   and ID = ?  ")), "false"
          ),
          new IfSqlNode(mixedContents(new TextSqlNode("   or NAME = ?  ")), "true"
          )
      )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 17
Source Project: Shop-for-JavaWeb   Source File: XMLMapperBuilder.java    License: MIT License 5 votes vote down vote up
public XMLMapperBuilder(InputStream inputStream,
		Configuration configuration, String resource,
		Map<String, XNode> sqlFragments) {
	this(new XPathParser(inputStream, true, configuration.getVariables(),
			new XMLMapperEntityResolver()), configuration, resource,
			sqlFragments);
}
 
Example 18
Source Project: mybatis   Source File: VelocitySqlSource.java    License: Apache License 2.0 5 votes vote down vote up
public VelocitySqlSource(Configuration configuration, String scriptText) {
  this.configuration = configuration;
  try {
    RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
    StringReader reader = new StringReader(scriptText);
    SimpleNode node = runtimeServices.parse(reader, "Template name");
    script = new Template();
    script.setRuntimeServices(runtimeServices);
    script.setData(node);
    script.initDocument();
  } catch (Exception ex) {
    throw new BuilderException("Error parsing velocity script", ex);
  }
}
 
Example 19
public MybatisSimpleQueryMapperBuilder(Configuration configuration,
		PersistentEntity<?, ?> persistentEntity, SimpleMybatisQuery query) {
	super(configuration, persistentEntity, query.getQueryMethod().getNamespace());

	method = query.getQueryMethod();
	stringQuery = query.getStringQuery();
	commandType = query.getCommandType();

}
 
Example 20
Source Project: nexus-public   Source File: MyBatisDataStore.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Loads the MyBatis configuration for this store.
 */
@VisibleForTesting
protected Configuration loadMyBatisConfiguration(final Environment environment) throws IOException {
  if (directories == null) {
    info("Using default MyBatis configuration");
    return new Configuration();
  }

  Path configPath = myBatisConfigPath(environment);

  info("Loading MyBatis configuration from {}", configPath);
  try (InputStream in = newInputStream(configPath); TcclBlock block = begin(getClass())) {
    return new XMLConfigBuilder(in, null, new Properties()).parse();
  }
}
 
Example 21
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTrimWHEREORWithLFForFirstCondition() throws Exception {
  final String expected = "SELECT * FROM BLOG WHERE \n ID = ?";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG"),
      new WhereSqlNode(new Configuration(),mixedContents(
          new IfSqlNode(mixedContents(new TextSqlNode("   or\n ID = ?  ")), "true"
              )
          )));
  BoundSql boundSql = source.getBoundSql(null);
  assertEquals(expected, boundSql.getSql());
}
 
Example 22
Source Project: mybaties   Source File: XMLConfigBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public Configuration parse() {
    //如果已经解析过了,报错
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
//  <?xml version="1.0" encoding="UTF-8" ?> 
//  <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
//  "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
//  <configuration> 
//  <environments default="development"> 
//  <environment id="development"> 
//  <transactionManager type="JDBC"/> 
//  <dataSource type="POOLED"> 
//  <property name="driver" value="${driver}"/> 
//  <property name="url" value="${url}"/> 
//  <property name="username" value="${username}"/> 
//  <property name="password" value="${password}"/> 
//  </dataSource> 
//  </environment> 
//  </environments>
//  <mappers> 
//  <mapper resource="org/mybatis/example/BlogMapper.xml"/> 
//  </mappers> 
//  </configuration>
    
    //根节点是configuration
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }
 
Example 23
Source Project: Aooms   Source File: RecordUpdate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void process() {
    MappedStatement mappedStatement = MetaObjectAssistant.getMappedStatement(metaObject);
    Object parameterObject = MetaObjectAssistant.getParameterObject(metaObject);
    Record record = (Record) parameterObject;

    String tableName = record.getGeneral(MyBatisConst.TABLE_NAME_PLACEHOLDER);
    String pkName = String.valueOf(record.getOrDefault(MyBatisConst.TABLE_PK_NAME_PLACEHOLDER, AoomsVar.ID));
    Object pkValue = record.get(pkName);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(" update ");
    stringBuilder.append(tableName); // tableName
    stringBuilder.append(" set {} ");
    stringBuilder.append(" where "+ pkName +" = #{"+ pkName +"} ");

    StringBuilder columns = new StringBuilder();
    int index = 0;
    Iterator<String> keyIterator = record.keySet().iterator();
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();
        if (index > 0) {
            columns.append(",");
        }
        columns.append(key).append(" = ").append("#{").append(key).append("}");
        index++;
    }

    String sql = StrUtil.format(stringBuilder, columns);
    //SqlSource sqlSource = new XMLLanguageDriver().createSqlSource(mappedStatement.getConfiguration(), sql, Map.class);
    Configuration configuration = MetaObjectAssistant.getConfiguration(metaObject);
    SqlSource sqlSource = configuration.getLanguageRegistry().getDefaultDriver().createSqlSource(mappedStatement.getConfiguration(), sql, Map.class);
    BoundSql boundSql = sqlSource.getBoundSql(parameterObject);

    MetaObjectAssistant.setDelegateBoundSql(metaObject,boundSql);
    MetaObjectAssistant.setDelegateParameterHandlerBoundSql(metaObject,boundSql);
}
 
Example 24
Source Project: mumu   Source File: MapperScanApplication.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 加载别名
 * @param configuration
 */
private void handleTypeAlias(Configuration configuration, XNode root) {
	log.info("load alias message...........................");
	TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
	XNode parent = root.evalNode("typeAliases");
	if(parent!=null){
		for (XNode child : parent.getChildren()) {
			if ("package".equals(child.getName())) {
				String typeAliasPackage = child.getStringAttribute("name");
				configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
				log.info("package:"+typeAliasPackage);
			} else {
				String alias = child.getStringAttribute("alias");
				String type = child.getStringAttribute("type");
				try {
					Class<?> clazz = Resources.classForName(type);
					if (alias == null) {
						typeAliasRegistry.registerAlias(clazz);
					} else {
						typeAliasRegistry.registerAlias(alias, clazz);
					}
					log.info("alias:"+alias+"   type:"+clazz);
				} catch (ClassNotFoundException e) {
					throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
				}
			}
		}
	}
}
 
Example 25
Source Project: mybaties   Source File: XmlExternalRefTest.java    License: 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();
}
 
Example 26
Source Project: mybaties   Source File: NonFullyQualifiedNamespaceTest.java    License: 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 27
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: 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 28
Source Project: mybatis   Source File: BoundSql.java    License: 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 29
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: 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 30
Source Project: mybatis   Source File: DynamicSqlSourceTest.java    License: 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());
}