1. 定义承载结果的Java类充当领域对象(不使用MyBatis的内置map)。
2.开发Mapper组件,也就是接口+XML(或注解)
3.获取SqlSession,在获取Mapper组件对象。
4.调用Mapper组件的方法操作数据库。
---------------------------------------------------------------------------------------------------------------------------------
实操一下,数据库名称mydept,数据表dept:

1.创建可以充当领域对象的JAVA类:entity.Dept

省略了无参构造器,全参构造器,getter/setter和toString。
2. 构建Mapper组件
定义dao.MyDeptMapper接口
public interface MyDeptMapper {int addDept(Dept dept);int updateDept(Dept dept);int removeDept(int id);Dept get(int id);List getAll();
}
定义XML文档,按照映射规则接口与XML文档要同名同包同id。
所以XML文档要建立在resources下的dao目录下,与java源文件目录下的dao.MyDeptMapper接口对应上。

然后要在mybatis-config.xml中描述清楚MyDeptMapper.xml的位置:
只需关注mybatis-config.xml中
随后可以开始编辑MyDeptMapper.xml的具体内容了:
insert into dept values(null,#{name},#{loc}) update dept set name=#{name}, loc=#{loc} where id=#{id} delete from dept where id = #{id}
这里只需注意两个点:
3. 获取SqlSession
String configXML = "mybatis-config.xml";
InputStream stream = Resources.getResourceAsStream(configXML);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
SqlSession sqlSession = sqlSessionFactory.openSession();
4.通过session调用Mapper组件操作数据库:
//省略了导包的相关代码 import dao.MyDeptMapper;
MyDeptMapper mapper = session.getMapper(MyDeptMapper.class);
List depts = mapper.getAll();
System.out.printf("%d rows.",depts.size());