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

The following examples show how to use org.apache.ibatis.session.SqlSessionFactory. 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
public static <E> MybatisBatchUpdater<E> createBatchUpdater(@NonNull SqlSessionFactory sessionFactory, @Nullable BatchMode batchType) {
    MybatisBatchUpdater<E> updater = null;
    if (batchType != null) {
        switch (batchType) {
            case SIMPLE:
                updater = new SimpleBatchUpdater<E>();
                break;
            case BATCH_SQL:
                updater = new BatchSqlBatchUpdater<E>();
                break;
            case JDBC_BATCH:
                updater = new JdbcBatchUpdater<E>();
                break;
            default:
                break;
        }
    }
    if (Objects.isNotNull(updater)) {
        updater.setSessionFactory(sessionFactory);
    }
    return updater;
}
 
Example 2
Source Project: mybatis   Source File: XmlExternalRefTest.java    License: Apache License 2.0 6 votes vote down vote up
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals(2, person.getPets().size());
    assertEquals((Integer)2, person.getPets().get(1).getId());

    Pet pet = personMapper.selectPet(1);
    assertEquals(Integer.valueOf(1), pet.getId());

    PetMapper petMapper = sqlSession.getMapper(PetMapper.class);
    Pet pet2 = petMapper.select(3);
    assertEquals((Integer)3, pet2.getId());
    assertEquals((Integer)2, pet2.getOwner().getId());
  } finally {
    sqlSession.close();
  }
}
 
Example 3
Source Project: SSO   Source File: MybatisSessionInstance.java    License: Apache License 2.0 6 votes vote down vote up
public static SqlSession getInstance() {
	if (sf == null) {
		synchronized (SqlSessionFactory.class) {
			if (sf == null) {
				try {
					Reader reader = Resources.getResourceAsReader(resource);
					sf = new SqlSessionFactoryBuilder().build(reader);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
			}
		}
	}
	return sf.openSession();
}
 
Example 4
/**
 * init interceptors
 */
@PostConstruct
void addInterceptors() {
    Interceptor interceptor = new MyBatisExecutePageableInterceptor();
    // set properties to interceptor
    interceptor.setProperties(myBatisPageableProperties.getProperties());

    for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
        // pre
        addPreInterceptors(sqlSessionFactory);
        // mybatis pageable interceptor
        sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        // post
        addPostInterceptors(sqlSessionFactory);
    }
}
 
Example 5
Source Project: mybatis   Source File: RefCursorTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRefCursor2() throws IOException {
    Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/refcursor/MapperConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        OrdersMapper mapper = sqlSession.getMapper(OrdersMapper.class);
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("orderId", 1);
        mapper.getOrder2(parameter);
        
        assertNotNull(parameter.get("order"));
        List<Order> orders = (List<Order>) parameter.get("order");
        assertEquals(1, orders.size());
        Order order = orders.get(0);
        assertEquals(3, order.getDetailLines().size());
    } finally {
        sqlSession.close();
    }
}
 
Example 6
Source Project: maintain   Source File: GjpaymentDatabaseConfig.java    License: MIT License 6 votes vote down vote up
@Bean(name = "gjpaymentSqlSessionFactory")
public SqlSessionFactory gjpaymentSqlSessionFactory() throws Exception {
	SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
	logger.info("gjpayment sqlsession--" + this.gjpaymentDataSource().hashCode());
	sqlSessionFactoryBean.setDataSource(this.gjpaymentDataSource());
	PageHelper pageHelper = new PageHelper();
	Properties properties = new Properties();
	properties.setProperty("dialect", "oracle");
	properties.setProperty("pageSizeZero", "true");
	properties.setProperty("reasonable", "false");
	properties.setProperty("params", "pageNum=pageHelperStart;pageSize=pageHelperRows;");
	properties.setProperty("supportMethodsArguments", "true");
	properties.setProperty("returnPageInfo", "none");
	pageHelper.setProperties(properties);
	Interceptor[] interceptors = new Interceptor[] { pageHelper };
	sqlSessionFactoryBean.setPlugins(interceptors);
	return sqlSessionFactoryBean.getObject();
}
 
Example 7
Source Project: mybatis   Source File: IncludeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testIncludes() throws Exception {
  String resource = "org/apache/ibatis/submitted/includes/MapperConfig.xml";
  Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  SqlSessionFactory sqlMapper = builder.build(reader);
  assertNotNull(sqlMapper);

  final SqlSession sqlSession = sqlMapper.openSession();
  try {
    final Integer result = sqlSession.selectOne("org.apache.ibatis.submitted.includes.mapper.selectWithProperty");
    Assert.assertEquals(Integer.valueOf(1), result);
  } finally {
    sqlSession.close();
  }
}
 
Example 8
Source Project: code   Source File: MybatisTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 测试mybatis环境
 */
public static void main(String[] args) throws Exception {
    // 1、读取配置文件
    InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
    // 2、创建SqlSessionFactory的建造者
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    // 3、使用建造者创建工厂对象SqlSessionFactory
    SqlSessionFactory factory = builder.build(in);
    // 4、使用SqlSessionFactory创建SqlSession对象
    SqlSession session = factory.openSession();
    // 5、使用SqlSession创建dao接口的代理对象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    // 6、使用代理对象执行sql查询
    System.out.println("基于XML配置");
    userMapper.findAll().forEach(System.out::println);
    System.out.println("基于注解配置");
    userMapper.findUsers().forEach(System.out::println);
    // 7、释放资源
    session.close();
    in.close();
}
 
Example 9
Source Project: springBoot-study   Source File: ClusterDataSourceConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
        throws Exception {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(clusterDataSource);
    //分页插件
    Interceptor interceptor = new PageInterceptor();
    Properties properties = new Properties();
    //数据库
    properties.setProperty("helperDialect", "mysql");
    //是否将参数offset作为PageNum使用
    properties.setProperty("offsetAsPageNum", "true");
    //是否进行count查询
    properties.setProperty("rowBoundsWithCount", "true");
    //是否分页合理化
    properties.setProperty("reasonable", "false");
    interceptor.setProperties(properties);
    sessionFactory.setPlugins(new Interceptor[] {interceptor});
    
    
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
    return sessionFactory.getObject();
}
 
Example 10
/**
 * SqlSessionFactory配置
 *
 * @return
 * @throws Exception
 */
@Bean(name = "read1SqlSessionFactory")
public SqlSessionFactory read1SqlSessionFactory(
        @Qualifier("read1DataSource") DataSource dataSource
) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    // 配置mapper文件位置
    sqlSessionFactoryBean.setMapperLocations(resolver.getResources(read1MapperLocations));

    //配置分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty("reasonable", "true");
    properties.setProperty("supportMethodsArguments", "true");
    properties.setProperty("returnPageInfo", "check");
    properties.setProperty("params", "count=countSql");
    pageHelper.setProperties(properties);

    //设置插件
    sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
    return sqlSessionFactoryBean.getObject();
}
 
Example 11
Source Project: SO   Source File: DatabaseConfig.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory SqlSessionFactory(@Qualifier("datasource") DataSource dataSource
            , ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // accur Could not resolve type alias in running jar
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);

        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                applicationContext.getResources("classpath:META-INF/mappers/*.xml")
        );
        // configuration 은 xml 파일로 처리
        sqlSessionFactoryBean.setConfigLocation(
                applicationContext.getResource("classpath:META-INF/mybatis-config.xml")
        );
//        sqlSessionFactoryBean.setConfigurationProperties(mybatisProperties());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.pineone.icbms.so.interfaces.database.model");

        return sqlSessionFactoryBean.getObject();
    }
 
Example 12
Source Project: mybaties   Source File: InsertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertAnnotated() throws Exception {
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/keycolumn/MapperConfig.xml");
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    InsertMapper mapper = sqlSession.getMapper(InsertMapper.class);
    Name name = new Name();
    name.setFirstName("Fred");
    name.setLastName("Flintstone");

    int rows = mapper.insertNameAnnotated(name);

    assertNotNull(name.getId());
    assertEquals(1, rows);
  } finally {
    sqlSession.close();
  }
}
 
Example 13
Source Project: mybatis   Source File: AutomaticLazyLoadingTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a session with the specified configuration and initialized the database.
 */
private void openSession(String aConfig) throws Exception {
  final String resource = "org/apache/ibatis/submitted/automatic_lazy_loading/ibatis-automatic-lazy-load-" + aConfig + ".xml";
  Reader batisConfigReader = Resources.getResourceAsReader(resource);

  SqlSessionFactory sqlSessionFactory;
  try {
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(batisConfigReader);
  } catch(Exception anException) {
    throw new RuntimeException("Mapper configuration failed, expected this to work: " + anException.getMessage(), anException);
  }

  SqlSession session = sqlSessionFactory.openSession();

  Connection conn = session.getConnection();
  ScriptRunner runner = new ScriptRunner(conn);
  runner.setLogWriter(null);
  runner.setErrorLogWriter(null);
  Reader createScriptReader = Resources.getResourceAsReader("org/apache/ibatis/submitted/automatic_lazy_loading/create.sql");
  runner.runScript(createScriptReader);

  sqlSession = sqlSessionFactory.openSession();
}
 
Example 14
Source Project: SO   Source File: DatabaseConfig.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory SqlSessionFactory(@Qualifier("datasource") DataSource dataSource
            , ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // accur Could not resolve type alias in running jar
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);

        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                applicationContext.getResources("classpath:META-INF/mappers/*.xml")
        );
        // configuration 은 xml 파일로 처리
        sqlSessionFactoryBean.setConfigLocation(
                applicationContext.getResource("classpath:META-INF/mybatis-config.xml")
        );
//        sqlSessionFactoryBean.setConfigurationProperties(mybatisProperties());
        sqlSessionFactoryBean.setTypeAliasesPackage("com.pineone.icbms.so.interfaces.database.model");

        return sqlSessionFactoryBean.getObject();
    }
 
Example 15
@Test
public void shouldNotReuseCachedSqlSessionIfNotConfigured() {
  final TestEngineCfg cfg = new TestEngineCfg();
  SqlSessionFactory existingSessionFactory = mock(SqlSessionFactory.class);

  // given
  ProcessEngineConfigurationImpl.cachedSqlSessionFactory = existingSessionFactory;

  // if
  cfg.initSqlSessionFactory();

  // then
  assertSame(existingSessionFactory, ProcessEngineConfigurationImpl.cachedSqlSessionFactory);
  assertNotSame(existingSessionFactory, cfg.getSqlSessionFactory());
}
 
Example 16
Source Project: dubbox   Source File: PluginsRegsiter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
	// 自动注册所有实现AutoRegister的监听器
	Map<String, SqlSessionFactory> beans = SpringContextHolder.getBeans(SqlSessionFactory.class);
	if (beans != null && beans.size() > 0) {
		for (String beanName : beans.keySet()) {
			SqlSessionFactory sessionFactory = beans.get(beanName);
			sessionFactory.getConfiguration().addInterceptor(SpringContextHolder.getBean(SQLRouterInterceptor.class));
		}
	}
}
 
Example 17
Source Project: oneops   Source File: CiEventReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
  ciEventReader = new CIEventReader();
  ciEventReader.init();
  SqlSessionFactory sessionFactory = mock(SqlSessionFactory.class);
  SqlSession session = mock(SqlSession.class);
  when(session.getMapper(CIMapper.class)).thenReturn(mapper);
  when(sessionFactory.openSession()).thenReturn(session);
  ciEventReader.setSessionFactory(sessionFactory);
}
 
Example 18
@Bean(DATABASE_PREFIX + "SqlSessionTemplate")
public SqlSessionTemplate getSqlSessionTemplate(@Qualifier(DATABASE_PREFIX + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
        return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
 
Example 19
@Bean(DATABASE_PREFIX + "SqlSessionTemplate")
public SqlSessionTemplate getSqlSessionTemplate(@Qualifier(DATABASE_PREFIX + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
        return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
 
Example 20
Source Project: mybatis   Source File: MultipleIncludeTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testMultipleIncludes(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    MultipleIncludePersonMapper personMapper = sqlSession.getMapper(MultipleIncludePersonMapper.class);
    Person person = personMapper.select(1);
    assertEquals((Integer)1, person.getId());
    assertEquals("John", person.getName());

  } finally {
    sqlSession.close();
  }
}
 
Example 21
Source Project: Milkomeda   Source File: SundialTweakConfig.java    License: MIT License 5 votes vote down vote up
@Autowired
public void configSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    MultiDataSourceTransactionFactory multiDataSourceTransactionFactory = new MultiDataSourceTransactionFactory();
    Pair<Field, Object> envFieldBundle = ReflectUtil.getFieldBundlePath(sqlSessionFactory, "configuration.environment");
    Environment originEnvironment = (Environment) envFieldBundle.getValue();
    Environment environment = new Environment(originEnvironment.getId(), multiDataSourceTransactionFactory, originEnvironment.getDataSource());
    Pair<Field, Object> confFieldBundle = ReflectUtil.getFieldBundlePath(sqlSessionFactory, "configuration");
    Object configuration = confFieldBundle.getValue();
    ReflectUtil.invokeMethod(configuration, "setEnvironment", new Class[]{Environment.class}, environment);
}
 
Example 22
Source Project: mybatis-generator-plus   Source File: HelloTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws FileNotFoundException {
	// Mapper的配置文件
	String resource = HelloTest.class.getResource("/mybatis-config.xml").getFile();
	// 使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
	InputStream is = new FileInputStream(resource);
	// 构建sqlSession的工厂
	SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
	sqlSession = sessionFactory.openSession();
	operateLogMapper = sqlSession.getMapper(OperateLogMapper.class);
	userVisitLogMapper = sqlSession.getMapper(UserVisitLogMapper.class);
}
 
Example 23
Source Project: mybaties   Source File: DynamicSqlSourceTest.java    License: 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 24
Source Project: mybatis   Source File: ResultMapExtendsTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testCrossReference(SqlSessionFactory sqlSessionFactory) throws Exception {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    ResultMapReferencePersonMapper personMapper = sqlSession.getMapper(ResultMapReferencePersonMapper.class);

    Pet pet = personMapper.selectPet(1);
    assertEquals(Integer.valueOf(1), pet.getId());

  } finally {
    sqlSession.close();
  }
}
 
Example 25
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
        throws Exception {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(clusterDataSource);
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
            .getResources(ClusterDataSourceConfig.MAPPER_LOCATION));
    return sessionFactory.getObject();
}
 
Example 26
Source Project: mybaties   Source File: DefaultResultHandlerTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
private SqlSessionFactory getSqlSessionFactoryXmlConfig(String resource) throws Exception {
  Reader configReader = Resources.getResourceAsReader(resource);
  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
  configReader.close();

  Connection conn = sqlSessionFactory.getConfiguration().getEnvironment().getDataSource().getConnection();
  initDb(conn);

  return sqlSessionFactory;
}
 
Example 27
@Bean(name = "courseSqlSessionFactory")
@Primary
public SqlSessionFactory courseSqlSessionFactory(@Qualifier("courseDataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    return bean.getObject();
}
 
Example 28
Source Project: pmq   Source File: InMemoryDbDatasourceConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "inMemoryDbSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("inMemoryDbDataSource") DataSource dataSource,SoaConfig soaConfig) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setPlugins(new Interceptor[] {new CatMybatisPlugin(soaConfig)});
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_XML_PATH));
    bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
    return bean.getObject();
}
 
Example 29
Source Project: demo-seata-springcloud   Source File: SeataAutoConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 初始化mybatis sqlSessionFactory
 * 
 * @param dataSourceProxy
 * @return
 * @throws Exception
 * @author sly
 * @time 2019年6月11日
 */
@Bean
public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
	SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
	factoryBean.setDataSource(dataSourceProxy);
	factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
	factoryBean.setTypeAliasesPackage("com.sly.seata.common.model");
	factoryBean.setTransactionFactory(new JdbcTransactionFactory());
	return factoryBean.getObject();
}
 
Example 30
@Bean(DATABASE_PREFIX + "SqlSessionTemplate")
public SqlSessionTemplate getSqlSessionTemplate(@Qualifier(DATABASE_PREFIX + "SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
        return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}