MyBatis1:MyBatis入门

MyBatis 是什么

MyBatis 是什么,MyBatis 的 jar 包中有它的官方文档,文档是这么描述 MyBatis 的:

MyBatis is a first class persistence framework with support for custom SQL, stored procedures
and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of
parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration
and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

翻译过来就是:MyBatis 是一款支持普通 SQL 查询、存储过程和高级映射的持久层框架。MyBatis 消除了几乎所有的 JDBC 代码、参数的设置和结果集的检索。MyBatis 可以使用简单的 XML 或注解用于参数配置和原始映射,将接口和 Java POJO(普通 Java 对象)映射成数据库中的记录。

本文先入门地搭建表、建立实体类、写基础的配置文件、写简单的 Java 类,从数据库中查出数据,深入的内容后面的文章再逐一研究。

 

建表、建立实体类

从简单表开始研究 MyBatis,所以我们先建立一张简单的表:

create table student
(
  studentId          int                        primary key     auto_increment    not null,
  studentName        varchar(20)                                                  not null,
  studentAge         int                                                          not null,
  studentPhone       varchar(20)                                                  not null
)charset=utf8

insert into student values(null, 'Jack', 20, '000000');
insert into student values(null, 'Mark', 21, '111111');
insert into student values(null, 'Lily', 22, '222222');
insert into student values(null, 'Lucy', 23, '333333');
commit;

一个名为 student 的表格,里面存放了 student 相关字段,当然此时我们需要有一个 Java 实体类与之对应:

public class Student
{
    private int        studentId;
    private String     studentName;
    private int        studentAge;
    private String    studentPhone;
</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Student()
{
    </span><span style="color: rgba(0, 0, 255, 1)">super</span><span style="color: rgba(0, 0, 0, 1)">();
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> Student(<span style="color: rgba(0, 0, 255, 1)">int</span> studentId, String studentName, <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> studentAge,
        String studentPhone)
{
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentId =<span style="color: rgba(0, 0, 0, 1)"> studentId;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentName =<span style="color: rgba(0, 0, 0, 1)"> studentName;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentAge =<span style="color: rgba(0, 0, 0, 1)"> studentAge;
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentPhone =<span style="color: rgba(0, 0, 0, 1)"> studentPhone;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> getStudentId()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> studentId;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setStudentId(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> studentId)
{
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentId =<span style="color: rgba(0, 0, 0, 1)"> studentId;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getStudentName()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> studentName;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setStudentName(String studentName)
{
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentName =<span style="color: rgba(0, 0, 0, 1)"> studentName;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> getStudentAge()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> studentAge;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> setStudentAge(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> studentAge)
{
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentAge =<span style="color: rgba(0, 0, 0, 1)"> studentAge;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getStudentPhone()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> studentPhone;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setStudentPhone(String studentPhone)
{
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.studentPhone =<span style="color: rgba(0, 0, 0, 1)"> studentPhone;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String toString()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span> "StudentId:" + studentId + "\tStudentName:" + studentName + 
        "\tStudentAge:" + studentAge + "\tStudentPhone:" +<span style="color: rgba(0, 0, 0, 1)"> studentAge;
}

}

注意,这里空构造方法必须要有,SqlSession 的 selectOne 方法查询一条信息的时候会调用空构造方法去实例化一个 domain 出来。OK,这样 student 表及其对应的实体类 Student.java 就创建好了。

 

写 config.xml 文件

在写 SQL 语句之前,首先得有 SQL 运行环境,因此第一步是配置 SQL 运行的环境。创建一个 Java 工程,右键 src 文件夹,创建一个普通文件,取个名字叫做 config.xml,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>
<typeAliases>
<typeAlias alias="Student" type="com.xrq.domain.Student"/>
</typeAliases>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">environments </span><span style="color: rgba(255, 0, 0, 1)">default</span><span style="color: rgba(0, 0, 255, 1)">="development"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">environment </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="development"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">transactionManager </span><span style="color: rgba(255, 0, 0, 1)">type</span><span style="color: rgba(0, 0, 255, 1)">="JDBC"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dataSource </span><span style="color: rgba(255, 0, 0, 1)">type</span><span style="color: rgba(0, 0, 255, 1)">="POOLED"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
            <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="driver"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="com.mysql.jdbc.Driver"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
            <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="url"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="jdbc:mysql://localhost:3306/test"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
            <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="username"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="root"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
            <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="password"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="root"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
        <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dataSource</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">environment</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">environments</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">mapper </span><span style="color: rgba(255, 0, 0, 1)">resource</span><span style="color: rgba(0, 0, 255, 1)">="student.xml"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">mappers</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</configuration>

这就是一个最简单的 config.xml 的写法。接着右键 src,创建一个普通文件,命名为 student.xml,和 mapper 里面的一致(resource 没有任何的路径则表示 student.xml 和 config.xml 同路径),student.xml 这么写:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.xrq.StudentMapper">
<select id="selectStudentById" parameterType="int" resultType="Student">
<![CDATA[
select * from student where studentId = #{id}
]]>
</select>
</mapper>

专门有一个 student.xml 表示 student 表的 sql 语句,当然也可以几张表共用一个.xml 文件,这个看自己的项目和个人喜好。至此,MyBatis 需要的两个.xml 文件都已经建立好,接下来需要做的就是写 Java 代码了。

 

Java 代码实现

首先要进入 MyBatis 的 jar 包:

第二个 MySql-JDBC 的 jar 包注意一下要引入,这个很容易忘记。

接着创建一个类,我起名字叫做 StudentOperator,由于这种操作数据库的类被调用频繁但是调用者之间又不存在数据共享的问题,因此使用单例会比较节省资源。为了好看,写一个父类 BaseOperator,SqlSessionFactory 和 Reader 都定义在父类里面,子类去继承这个父类:

public class BaseOperator
{
    protected static SqlSessionFactory ssf;
    protected static Reader reader;
</span><span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)">
{
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">
    {
        reader </span>= Resources.getResourceAsReader("config.xml"<span style="color: rgba(0, 0, 0, 1)">);
        ssf </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> SqlSessionFactoryBuilder().build(reader);
    } 
    </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (IOException e)
    {
        e.printStackTrace();
    }
}

}

然后创建子类 StudentOperator:

public class StudentOperator extends BaseOperator
{
    private static StudentOperator instance = new StudentOperator();
</span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> StudentOperator()
{
    
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> StudentOperator getInstance()
{
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> instance;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> Student selectStudentById(<span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> studentId)
{
    SqlSession ss </span>=<span style="color: rgba(0, 0, 0, 1)"> ssf.openSession();
    Student student </span>= <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)">
    {
        student </span>= ss.selectOne("com.xrq.StudentMapper.selectStudentById", 1<span style="color: rgba(0, 0, 0, 1)">);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">finally</span><span style="color: rgba(0, 0, 0, 1)">
    {
        ss.close();
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> student;
}

}

这个类里面做了两件事情:

1、构造一个 StudentOperator 的单实例

2、写一个方法根据 studentId 查询出一个指定的 Student

 

验证

至此,所有步骤全部就绪,接着写一个类来验证一下:

public class MyBatisTest
{
    public static void main(String[] args)
    {System.out.println(StudentOperator.getInstance().selectStudentById(1));}
}

运行结果为:

StudentId:1    StudentName:Jack    StudentAge:20    StudentPhone:20

看一下数据库中的数据:

数据一致,说明以上的步骤都 OK,MyBatis 入门完成,后面的章节,将会针对 MyBatis 的使用细节分别进行研究。