Java Code Examples for org.apache.ibatis.session.SqlSessionFactory#getConfiguration()

The following examples show how to use org.apache.ibatis.session.SqlSessionFactory#getConfiguration() . 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: 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 2
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 3
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 4
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 5
Source File: TestSqlDynamicAttributes.java    From soabase with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception
{
    try ( InputStream stream = Resources.getResource("test-mybatis.xml").openStream() )
    {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
        mybatisConfiguration.addMapper(AttributeEntityMapper.class);
        session = sqlSessionFactory.openSession(true);

        AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class);
        mapper.createTable();

        dynamicAttributes = new SqlDynamicAttributes(session, Collections.singletonList("test"));
        dynamicAttributes.start();
    }
}
 
Example 6
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private DynamicSqlSource createDynamicSqlSource(SqlNode... contents) throws IOException, SQLException {
  createBlogDataSource();
  final String resource = "org/apache/ibatis/builder/MapperConfig.xml";
  final Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
  Configuration configuration = sqlMapper.getConfiguration();
  MixedSqlNode sqlNode = mixedContents(contents);
  return new DynamicSqlSource(configuration, sqlNode);
}
 
Example 7
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private DynamicSqlSource createDynamicSqlSource(SqlNode... contents) throws IOException, SQLException {
  createBlogDataSource();
  final String resource = "org/apache/ibatis/builder/MapperConfig.xml";
  final Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
  Configuration configuration = sqlMapper.getConfiguration();
  MixedSqlNode sqlNode = mixedContents(contents);
  return new DynamicSqlSource(configuration, sqlNode);
}
 
Example 8
Source File: ShortNameTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration() throws IOException {
    Reader configReader = Resources
    .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MapperConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
    configReader.close();
    return sqlSessionFactory.getConfiguration();
}
 
Example 9
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 10
Source File: MockDatabase.java    From soabase with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ParameterCanBeLocal")
public static void main(String[] args) throws Exception
{
    ExampleAppBase.checkNullConsole();

    args = new String[]
        {
            "--database.0",
            "mem:test",
            "--dbname.0",
            "xdb",
            "--port",
            "10064"
        };
    Server.main(args);

    SqlSession session;
    try (InputStream stream = Resources.getResource("example-mybatis.xml").openStream())
    {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
        mybatisConfiguration.addMapper(AttributeEntityMapper.class);
        session = sqlSessionFactory.openSession(true);
    }

    AttributeEntityMapper mapper = session.getMapper(AttributeEntityMapper.class);
    mapper.createTable();

    mapper.insert(new AttributeEntity("test", "global"));
    mapper.insert(new AttributeEntity("test2", "hello", "one"));
    mapper.insert(new AttributeEntity("test2", "goodbye", "two"));

    List<AttributeEntity> attributeEntities = mapper.selectAll();
    System.out.println(attributeEntities);

    System.out.println("Running...");
    Thread.currentThread().join();
}
 
Example 11
Source File: SqlBundle.java    From soabase with Apache License 2.0 5 votes vote down vote up
@Override
public void run(T configuration, Environment environment) throws Exception
{
    SqlConfiguration sqlConfiguration = ComposedConfigurationAccessor.access(configuration, environment, SqlConfiguration.class);
    try
    {
        try ( InputStream stream = Resources.getResource(sqlConfiguration.getMybatisConfigUrl()).openStream() )
        {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
            Configuration mybatisConfiguration = sqlSessionFactory.getConfiguration();
            mybatisConfiguration.addMapper(AttributeEntityMapper.class);
            final SqlSession session = sqlSessionFactory.openSession(true);

            SoaBundle.getFeatures(environment).putNamed(session, SqlSession.class, sqlConfiguration.getName());
            Managed managed = new Managed()
            {
                @Override
                public void start() throws Exception
                {

                }

                @Override
                public void stop() throws Exception
                {
                    session.close();
                }
            };
            environment.lifecycle().manage(managed);
        }
    }
    catch ( Exception e )
    {
        log.error("Could not initialize MyBatis", e);
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: OurbatisLoader.java    From ourbatis with Apache License 2.0 5 votes vote down vote up
/**
 * Get an instance of o through which mapper can be loaded into the mybatis container
 * 
 * @param sqlSessionFactory	
 * 			Creates an SqlSession out of a connection or a DataSource
 * @param baseTemplateUri
 * 			The uri to the template, which is the relative path of the template under the classpath
 * @param mapperPacketUri
 * 			The path of mapper's package, example 'org.nico.ourbatis.mapper', Store the Mapper interface internally
 */
public OurbatisLoader(SqlSessionFactory sqlSessionFactory, String baseTemplateUri, String mapperLocations) {
	this.sqlSessionFactory = sqlSessionFactory;
	this.configuration = sqlSessionFactory.getConfiguration();
	this.mappers = new LinkedHashMap<Table, String>();
	this.mapper = new MapperMapping();
	this.noel = new Noel();
	this.baseTemplateUri = baseTemplateUri;
	this.mapperLocations = mapperLocations;
	this.baseTemplateContent = StreamUtils.convertToString(this.baseTemplateUri);
	log.debug("Start processing the data source session factory " + sqlSessionFactory);
}
 
Example 13
Source File: ShortNameTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration() throws IOException {
    Reader configReader = Resources
    .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/MapperConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
    configReader.close();
    return sqlSessionFactory.getConfiguration();
}
 
Example 14
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 15
Source File: MapperLoader.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
public void reloadXML() throws Exception {
	SqlSessionFactory factory = context.getBean(SqlSessionFactory.class);
	Configuration configuration = factory.getConfiguration();
	// 移除加载项
	removeConfig(configuration);
	// 重新扫描加载
	for (String basePackage : basePackages) {
		Resource[] resources = getResource(basePackage, XML_RESOURCE_PATTERN);
		if (resources != null) {
			for (int i = 0; i < resources.length; i++) {
				if (resources[i] == null) {
					continue;
				}
				try {
					XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resources[i].getInputStream(),
							configuration, resources[i].toString(), configuration.getSqlFragments());
					xmlMapperBuilder.parse();
				} catch (Exception e) {
					throw new NestedIOException("Failed to parse mapping resource: '" + resources[i] + "'", e);
				} finally {
					ErrorContext.instance().reset();
				}
			}
		}
	}

}
 
Example 16
Source File: MapperScannerConfigurer.java    From azeroth with Apache License 2.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    super.afterPropertiesSet();
    SqlSessionFactory sqlSessionFactory = context.getBean(sqlSessionFactoryName,
            SqlSessionFactory.class);
    Configuration configuration = sqlSessionFactory.getConfiguration();
    //
    new GeneralSqlGenerator(configuration).generate();
}
 
Example 17
Source File: MapperScannerWithSharding.java    From tsharding with MIT License 4 votes vote down vote up
private void initSqlSessionFactories(ConfigurableListableBeanFactory beanFactory) throws Exception {
    Map<String, SqlSessionFactory> sqlSessionFactories = new HashMap<>(this.dataSourceLookup.getMapping().size());

    ReadWriteSplittingDataSource defaultDataSource = null;
    SqlSessionFactory defaultSqlSessionFactory = null;
    for (ReadWriteSplittingDataSource dataSource : this.dataSourceLookup.getMapping().values()) {

        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setMapperLocations(mapperLocations);
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setTypeAliasesPackage(this.packageName + ".domain.entity");

        // init 初始化所有sql对应的元数据、资源(sqlNode, sqlSource, mappedStatement)等
        sessionFactoryBean.afterPropertiesSet();

        if (defaultDataSource == null) {
            //第一个
            defaultDataSource = dataSource;
            defaultSqlSessionFactory = sessionFactoryBean.getObject();
        } else {
            SqlSessionFactory newSqlSessionFactory = sessionFactoryBean.getObject();
            Field conf = newSqlSessionFactory.getClass().getDeclaredField("configuration");
            conf.setAccessible(true);
            Configuration newConfiguration = (Configuration) conf.get(newSqlSessionFactory);
            Field mappedStatementField = newConfiguration.getClass().getDeclaredField("mappedStatements");

            //去掉final修饰符
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt( mappedStatementField,  mappedStatementField.getModifiers() & ~Modifier.FINAL);
             mappedStatementField.setAccessible(true);

            //后续的元数据复用
            Configuration defaultConfiguration = defaultSqlSessionFactory.getConfiguration();
            Map<String, MappedStatement> reUsedMappedStatement = (Map)  mappedStatementField.get(defaultConfiguration);
            mappedStatementField.set(newConfiguration, reUsedMappedStatement);
        }
        beanFactory.registerSingleton(dataSource.getName() + "SqlSessionFactory", sessionFactoryBean);
        sqlSessionFactories.put(dataSource.getName(), sessionFactoryBean.getObject());
        defaultSqlSessionFactory = sessionFactoryBean.getObject();
    }

    this.sqlSessionFactoryLookup = new SqlSessionFactoryLookup(sqlSessionFactories);
}