在spring/springboot中使用mybatis时,只需要填写mybatis依赖,数据库配置以及相关mybatis配置信息,重写下sqlSessionFactory就可以使用了。但是在不使用spring的项目中怎么使用纯javaConfig配置mybatis,之前没有遇到过,这次做下记录。
众所周知,方法的使用都是实例调用或者静态类方法调用。这里其实和Spring相同,只不过spring是它创建管理了SqlSessionFactory的bean。这里还是写一个方法去获得SqlSessionFactory,在SqlSessionFactory中需要配置PooledDataSource相关数据,在mybatis配置中需要定义有哪些mapper,之后才能在这些mapper中获取相关方法。
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory initSqlSessionFactory(DBConfigInfo dbConfiguration) {
if (sqlSessionFactory == null) {
//这里是配置jdbc的相关配置
PooledDataSource pooledDataSource = new PooledDataSource();
pooledDataSource.setDriver("com.mysql.jdbc.Driver");
pooledDataSource.setUrl(dbConfiguration.getUrl());
pooledDataSource.setUsername(dbConfiguration.getUserName());
pooledDataSource.setPassword(dbConfiguration.getUserPassword());
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, pooledDataSource);
Configuration configuration = new Configuration(environment);
//配置驼峰法映射属性字段
configuration.setMapUnderscoreToCamelCase(true);
//这里是初始化了一部分系统定义的别名
configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
//这里是添加扫描的Mapper文件
configuration.addMapper(StudentMapper.class);
//构建相应的sqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
return sqlSessionFactory;
}
}
在获取到sqlSessionFactory后则需要获取对应的SqlSession
public static SqlSession getSession(){
if (sqlSessionFactory == null){
DBConfiguration dBConfiguration = DBConfiguration.getInstance();
initSqlSessionFactory(dBConfiguration.getConfigInfo());
}
return sqlSessionFactory.openSession();
}
从SqlSession中获取相应的Mapper使用Mapper中的方法。
SqlSession sqlSession = MybatisUtils.getSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = mapper.selectAll();
sqlSession.commit();
sqlSession.close();
对应的StudentMapper
public interface StudentMapper {
@Select("select * from student")
List<Student> selectAll();
}