首页  

mybatis 代码方式创建 SqlSessionFactory     所属分类 mybatis 浏览量 907
创建 SqlSessionFactory 两种方式
1 使用 mybatis-config.xml 配置文件 
2 使用 代码 配置


使用 mybatis-config.xml 配置文件 
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 使用配置文件创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		
使用代码配置

	private static SqlSessionFactory buildSqlSessionFactory() throws Exception {
		// 连接池
		PooledDataSource dataSource = new PooledDataSource();
		dataSource.setDriver("org.h2.Driver");
		dataSource.setUsername("sa");
		dataSource.setPassword("");
		dataSource.setUrl("jdbc:h2:mem:testdb");
		// dataSource.setDefeultAutoCommit(false);
		// MyBatis JDBC 事务
		TransactionFactory transactionFactory = new JdbcTransactionFactory();
		Environment environment = new Environment("dev", transactionFactory, dataSource);
		//
		Configuration configuration = new Configuration(environment);
		// MyBatis 类型别名
		// configuration.getTypeAliasRegistry().registerAlias("user",
		// UserDO.class);
		// configuration.addMapper(UserMapper.class);
		Set<String> mappers = new LinkedHashSet<>();
		mappers.add("mapper/UserMapper.xml");
		for (String resource : mappers) {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
					configuration.getSqlFragments());
			mapperParser.parse();
			inputStream.close();
		}

		SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
		return SqlSessionFactory;
	}


完整代码
https://gitee.com/dyyx/demos/blob/master/mybatis/src/main/java/dyyx/MybatisTest.java

上一篇     下一篇
SpringBoot定时任务 schedule

mybatis独立使用(不依赖spring)

mybatis中 DefaultSqlSessionFactory和SqlSessionManager的区别

springboot mybatis 多数据源实例

贝尔宾团队角色理论:优秀团队的9种角色

RocketMQ Kafka 简单比较