
1.3 第一个MyBatis项目
项目案例:新建项目mybatis11,查询MySQL数据库studentdb中的表student中的所有学生信息,在控制台输出。(项目源码参见本书配套资源:第1章/第1个mybatis项目/mybatis11)
实现步骤:
(1)在MySQL中创建数据库studentdb,创建表student,并添加若干测试用数据记录,SQL语句如下:
CREATE DATABASE studentdb;
USE studentdb ;
DROP TABLE IF EXISTS student ;
CREATE TABLE student (
id int(11) NOT NULL,
studentname varchar(20) DEFAULT NULL,
gender char(2) DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY ( id )
)
insert into student ( id , studentname , gender , age ) values (1,’张飞’,’男’,18),(2,'李白’,’男’,20),(3,’张无忌’,’男’,19),(4,’赵敏’,’女’,17);
(2)在Eclipse中新建Web项目mybatis11,将下载的与MyBatis有关的JAR包以及MySQL数据库驱动JAR包全部导入(复制)到目录WebContent/WEB-INF/lib下。完成后的lib下的JAR包清单如图1.3所示。

图1.3 搭建MyBatis项目所需JAR包清单
【注意】将JAR包复制到lib下并不意味着大功告成,还需选中全部JAR包,再单击鼠标右键在弹出的菜单中选择Build Path,选择Add to Build Path添加到构建路径。
(3)为了方便查看控制台输出SQL语句,还要配置log4j,在项目目录src下创建log4j.properties文件,输入内容如下:
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.lifeng=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
其中log4j.logger.com.lifeng=DEBUG里面的com.lifeng是包名,根据项目不同包名也会不同。本项目的类放在包com.lifeng下。DEBUG是日志记录的一种级别,表示可以显示所执行的SQL语句、参数值、对数据库的影响等信息,若改为TRACE级别,则还可进一步显示查询出的每条记录的每个字段名及值。
以上内容无须死记,可在下载的mybatis-3.4.5文件夹里的mybatis-3.4.5.pdf文件的Logging节里找到模板,再简单修改即可。
(4)在项目src目录下新建包com.lifeng.entity,创建实体类Student如下:
package com.lifeng.entity;
public class Student {
private String sid;
private String sname;
private String sex;
private int age;
public Student(){}
public Student(String sid,String sname,String sex,int age){
this.sid=sid;
his.sname=sname;
his.sex=sex;
his.age=age;
}
public void show(){
System.out.println("学生编号:"+sid+" 学生姓名:"+sname+" 学生性别:"+sex+" 学生年龄:"+age);
}
//省略setter,getter方法
}
(5)新建包com.lifeng.dao,新建DAO层接口IStudentDao,代码如下所示:
public interface IStudentDao {
public List<Student> findAllStudents();//查找全部学生
}
(6)在包com.lifeng.dao下创建映射文件StudentMapper.xml,代码及其解释如下:

映射文件主要实现SQL语句与Java对象之间的映射,使SQL语句查询出来的关系型数据能封装成Java对象。映射文件通常用POJO+Mapper命名,一般在DAO层中与接口放在一起。这里POJO为Student,所以映射文件名称定为StudentMapper.xml。
映射文件中,<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis. org/dtd/mybatis-3-mapper.dtd">是映射文件的约束信息,可以从MyBatis解压文件中的mybatis-3.4.5.pdf文档中找到,在该文档中搜索“mybatis-3-mapper.dtd”关键字,即可找到映射文件的约束。
图1.4所示是从该PDF文档中搜索到的,直接复制过来即可。

图1.4 映射文件的约束信息模板
映射文件中的一级标签<mapper></mapper>里面可包含多对<select>标签或者<insert><delete><update>等标签。
<mapper>标签的namepace属性,用于标识映射文件,通常其值设置成对应接口的全路径名称。<select></select>标签用于设计SQL语句,其标签内部只能是select查询语句,同理<insert></insert>标签内部只能是insert语句,<update></update>标签内部只能是update语句,<delete></delete>标签内部只能是delete语句。
<select><insert><delete><update>等标签的id属性用于唯一标识该SQL语句块,Java代码使用该标识来找到对应的SQL语句块。其值设置成与接口中对应的方法名称一致。
(7)在src下新建XML文件mybatis-config.xml作为主配置文件,完整代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置环境,默认环境id为development -->
<environments default="development">
<environment id="development">
<!-- 配置事务管理类型为 JDBC -->
<transactionManager type="JDBC"/>
<!-- 配置数据源类型为连接池 -->
<dataSource type="POOLED">
<!-- 分别配置数据库连接的驱动,url,用户名,密码 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/studentdb? characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 配置映射文件的位置,可以有多个映射文件 -->
<mappers>
<mapper resource="com/lifeng/dao/StudentMapper.xml"/>
</mappers>
</configuration>
上边的代码看起来很多,但无须死记,相关的模板可以从 MyBatis 下载文件解压目录下的mybatis-3.4.5.pdf文档中找到,在该文档中搜索“mybatis-3-config.dtd”关键字,即可找到映射文件的模板,如图1.5所示。上面代码第2~3行为主配置文件约束信息,提供有模板,其他部分如数据库连接的配置同样可参考文档mybatis-3.4.5.pdf中的模板。

图1.5 主配置文件模板
使用时只需把整个模板的内容复制过来再稍加修改就可以了。大部分内容不用改动,这里只修改了数据库连接的4条配置,给出了具体的数据库连接信息,以替换模板中的${}占位符。
<property name="driver" value="com.mysql.jdbc.Driver"/>
<propertyname="url"value="jdbc:mysql://localhost:3306/studentdb?characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
此外还修改了<mapper>节点,用于指出映射文件的全路径名(位置)。
<mapper resource="com/lifeng/dao/StudentMapper.xml"/>
【注意】如果一个项目有多个映射文件,则主配置文件需要多个<mapper>节点。这里的包路径用到符号“/”,而不是“.”。主配置文件名可以随意命名,但通常命名为mybatis-config.xml。
(8)创建DAO层实现类StudentDaoImpl.java,代码如下:
public class StudentDaoImpl implements IStudentDao{
@Override
public List<Student> findAllStudents() {
SqlSession session = null;
List<Student> list = new ArrayList<Student>();
try {
//1.读取主配置文件mybatis-config.xml
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
//2.根据主配置文件mybatis-config.xml构建SqlSessionFactory对象factory
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(reader);
//3.根据SqlSessionFactory对象创建SqlSession对象session
session = factory.openSession();
//4.调用SqlSession对象session的selectList方法执行查询数据库的操作,返回映射后的结果集合
list = session.selectList("com.lifeng.dao.IStudentDao.findAllStudents");
} catch (IOException e1) {
e1.printStackTrace();
}
return list;
}
}
上述代码中的session.selectList()是SqlSession类的方法,用于查询记录集合。
(9)创建测试类TestStudent1,新建包com.lifeng.test,包下新建类TestStudent1,代码如下:
public class TestStudent1 {
public static void main(String[] args) {
findAllStudents();
}
public static void findAllStudents(){
IStudentDao studentDao=new StudentDaoImpl();
List<Student> sList=studentDao.findAllStudents();
for(int i=0;i<sList.size();i++){
sList.get(i).show();
}
}
}
运行测试类TestStudent1结果如下。
DEBUG [main] - ==> Preparing: SELECT id as sid, studentname as sname, gender as sex, age FROM STUDENT
DEBUG [main] - ==> Parameters:
DEBUG [main] - <== Total: 4
学生编号:1 学生姓名:张飞 学生性别:男 学生年龄:18
学生编号:2 学生姓名:李白 学生性别:男 学生年龄:20
学生编号:3 学生姓名:张无忌 学生性别:男 学生年龄:19
学生编号:4 学生姓名:赵敏 学生性别:女 学生年龄:17
可见,数据库中的记录全都读出来了,由于之前配置了log4j,级别为DEBUG,所以SQL查询语句、参数、受影响记录数也显示出来了,方便程序员查看效果与检查调试。如果将级别改为TRACE,则结果如下:
DEBUG [main] - ==> Preparing: SELECT id as sid, studentname as sname, gender as sex, age FROM STUDENT
DEBUG [main] - ==> Parameters:
TRACE [main] - <== Columns: sid, sname, sex, age
TRACE [main] - <== Row: 1, 张飞, 男, 18
TRACE [main] - <== Row: 2, 李白, 男, 20
TRACE [main] - <== Row: 3, 张无忌, 男, 19
TRACE [main] - <== Row: 4, 赵敏, 女, 17
DEBUG [main] - <== Total: 4
学生编号:1 学生姓名:张飞 学生性别:男 学生年龄:18
学生编号:2 学生姓名:李白 学生性别:男 学生年龄:20
学生编号:3 学生姓名:张无忌 学生性别:男 学生年龄:19
学生编号:4 学生姓名:赵敏 学生性别:女 学生年龄:17
可见级别改为TRACE后,显示的SQL更为详细,本项目无须太过详细,改回DEBUG即可。