1. 引入jar包
如果是非maven项目只需引入 mybatis-x.x.x.jar包到classpath目录下
如果是maven项目则需引入maven依赖
org.mybatis mybatisx.x.x 注:不要忘记引入对应数据库的驱动
2. 添加mybatis全局配置文件mybatis-config.xml
3.写Mapper.xml文件对应的sql语句
select * from dual
4. 获取sqlSessionFactory并连接数据库
@Test
public void test1() throws IOException {
String path="mybatis-config.xml";
InputStream is= Resources.getResourceAsStream(path);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
try{
SqlSession sqlSession = sqlSessionFactory.openSession();
List objects =sqlSession.selectList("com.XX.queryXX");
System.out.println(objects);
}catch (Exception ex){
ex.printStackTrace();
}
}
接口方式调用
1.添加调用接口和xml
配置XML与XML对应接口 package mapper; public interface contentMapper { List queryBannder(); }
2.配置接口信息在mybatis配置文件中
3. 获取sqlSessionFactory
@Test
public void test2() throws IOException {
String path="mybatis-config.xml";
InputStream is= Resources.getResourceAsStream(path);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
XXMapper mapper = sqlSession.getMapper(XXMapper.class);
List XXVos = mapper.queryXX();
System.out.println(XXVos );
}



