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,所以我们先建立一张简单的表:

1
2
3
4
5
6
7
8
9
10
11
12
13
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实体类与之对应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Student
{
    private int        studentId;
    private String     studentName;
    private int        studentAge;
    private String    studentPhone;
 
    public Student()
    {
        super();
    }
 
    public Student(int studentId, String studentName, int studentAge,
            String studentPhone)
    {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentAge = studentAge;
        this.studentPhone = studentPhone;
    }
 
    public int getStudentId()
    {
        return studentId;
    }
 
    public void setStudentId(int studentId)
    {
        this.studentId = studentId;
    }
 
    public String getStudentName()
    {
        return studentName;
    }
 
    public void setStudentName(String studentName)
    {
        this.studentName = studentName;
    }
 
    public int getStudentAge()
    {
        return studentAge;
    }
 
    public void setStudentAge(int studentAge)
    {
        this.studentAge = studentAge;
    }
 
    public String getStudentPhone()
    {
        return studentPhone;
    }
 
    public void setStudentPhone(String studentPhone)
    {
        this.studentPhone = studentPhone;
    }
 
    public String toString()
    {
        return "StudentId:" + studentId + "\tStudentName:" + studentName +
            "\tStudentAge:" + studentAge + "\tStudentPhone:" + studentAge;
    }
}

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

写config.xml文件

在写SQL语句之前,首先得有SQL运行环境,因此第一步是配置SQL运行的环境。创建一个Java工程,右键src文件夹,创建一个普通文件,取个名字叫做config.xml,config.xml里这么写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?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>
 
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
 
    <mappers>
        <mapper resource="student.xml"/>
    </mappers>
</configuration>

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

1
2
3
4
5
6
7
8
9
10
11
<?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都定义在父类里面,子类去继承这个父类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BaseOperator
{
    protected static SqlSessionFactory ssf;
    protected static Reader reader;
 
    static
    {
        try
        {
            reader = Resources.getResourceAsReader("config.xml");
            ssf = new SqlSessionFactoryBuilder().build(reader);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

然后创建子类StudentOperator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class StudentOperator extends BaseOperator
{
    private static StudentOperator instance = new StudentOperator();
 
    private StudentOperator()
    {
 
    }
 
    public static StudentOperator getInstance()
    {
        return instance;
    }
 
    public Student selectStudentById(int studentId)
    {
        SqlSession ss = ssf.openSession();
        Student student = null;
        try
        {
            student = ss.selectOne("com.xrq.StudentMapper.selectStudentById", 1);
        }
        finally
        {
            ss.close();
        }
        return student;
    }
}

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

1、构造一个StudentOperator的单实例

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

验证

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

1
2
3
4
5
6
7
public class MyBatisTest
{
    public static void main(String[] args)
    {
        System.out.println(StudentOperator.getInstance().selectStudentById(1));
    }
}

运行结果为:

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

看一下数据库中的数据:

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

MyBatis(1):MyBatis入门的更多相关文章

  1. MyBatis(1)——快速入门

    MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...

  2. 【mybatis深度历险系列】mybatis的框架原理+入门程序解析

    在前面的博文中,小编介绍了springmvc的相关知识点,在今天这篇博文中,小编将介绍一下mybatis的框架原理,以及mybatis的入门程序,实现用户的增删改查,她有什么优缺点以及mybatis和 ...

  3. mybatis的快速入门

    说明: 在这个部分,会写个简单的入门案例. 然后,会重新写一个,更加严格的程序案例. 一:案例一 1.最终的目录结构 2.新建一个普通的Java项目,并新建lib 在项目名上右键,不是src. 3.导 ...

  4. (转) MyBatis(1)——快速入门

    MyBatis 简介 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...

  5. Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建

    目录 Spring MVC+Spring+Mybatis+MySQL(IDEA)入门框架搭建 0.项目准备 1.数据持久层Mybatis+MySQL 1.1 MySQL数据准备 1.2 Mybatis ...

  6. MyBatis(1)-简单入门

    简介 什么是 MyBatis ? MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.My ...

  7. (转)MyBatis框架的学习(二)——MyBatis架构与入门

    http://blog.csdn.net/yerenyuan_pku/article/details/71699515 MyBatis框架的架构 MyBatis框架的架构如下图: 下面作简要概述: S ...

  8. 【Mybatis】mybatis3入门

    mybatis简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可 ...

  9. 【MyBatis】MyBatis 入门

    MyBatis 入门 文章源码 软件框架 软件框架伴随着软件工程的发展而出现,所谓的软件框架,是提取了特定领域的软件的共性部分所形成的软件体系,它并不是一个成熟的软件,更像是一个半成品.开发者在框架之 ...

  10. MyBatis笔记----MyBatis 入门经典的两个例子: XML 定义与注解定义

    ----致敬MyBatis官方开放文档让大家翻译,不用看书直接看文档就行了,mybatis的中文文档还需要完备的地方 简介 什么是 MyBatis ? MyBatis 是支持定制化 SQL.存储过程以 ...

随机推荐

  1. Python之路,Day21 - 常用算法学习

    Python之路,Day21 - 常用算法学习   本节内容 算法定义 时间复杂度 空间复杂度 常用算法实例 1.算法定义 算法(Algorithm)是指解题方案的准确而完整的描述,是一系列解决问题的 ...

  2. bootstrap栅格布局

    <!DOCTYPE html> <html lang="en"> <head> <!-- //简介:boststrap内置了一套响应式,移 ...

  3. (转)Call to undefined function mb_convert_encoding()

    需要先enable mbstring 扩展库 在 php.ini里将; extension=php_mbstring.dll 前面的 ; 去掉mb_convert_encoding 可以指定多种输入编 ...

  4. crud的意识

    CRUD说的就是增查改删C:Create 增加对应CREATE TBL ...: ADD TBL IN (...) VALUES (...)R:Retrieve查询SELECT * from TBLU ...

  5. UITextView textViewShouldEndEditing

    最近做到UITextView, 在取消键盘事件上我以为和UITextField差不多,于是我这样写: UITextView *textView = [[UITextView alloc] initWi ...

  6. windows批处理命令之ren

    1.批处理批量修改文件后缀名(假设我需要把一个文件夹中的很多txt文件改为sql文件): 1)在需要被处理的文件的文件夹里先新建一个txt文本,然后在文本中写入: ren *.txt *.sql 2) ...

  7. 面向对象设计模式之Facade外观模式(结构型)

    动机:有些系统组件的客户和组件中各种复杂的子系统有了过多的的耦合,随着外部客户程序  和个子系统的演化,这种过多的耦合面临很多变化的挑战:如何简化外部客户程序和系统的交互接口?  如何将外部客户程序的 ...

  8. javascript 键值对

    <script type="text/javascript"> var arr = new Array(); arr['cn'] = '中国'; arr['usa'] ...

  9. @font-face扒站的步骤

    今天模仿百度首页手机版的时候遇到的@font-face的问题,现在整理一下. 问题:图中红色区域,在拷贝F12样式的时候,并没有出现这些小图标.        图1:百度的效果             ...

  10. 深入Java虚拟机读书笔记第三章安全

    为什么需要安全性 Java的安全模型是其多个重要结构特点之一,它使Java成为适于网络环境的技术.Java安全模型侧重于保护终端用户免受从网络下载的.来自不可靠来源的.恶意程序(以及善于程序中的bug ...