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字符串replace()方法

    python字符串replace()方法 >>> help(str.replace)Help on method_descriptor:replace(...)    S.repla ...

  2. SpringMVC11文件上传

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% ...

  3. php 在web端读出pdf 与各种文件下载

    单纯的下载功能实现 <?php // 表示调用文本类型为pdf的应用 header('Content-type: application/pdf'); // 这句可以输出下载页面进行下载 hea ...

  4. sqlserver2008附加数据库——错误3415

    权限问题, 在其文件,右击属性>安全>编辑>添加>加一个everyone单击确定>其完全控制, 这样给每个用户权限 ---来自凌波小屋----冯和超笔记-----

  5. Skew Join与Left Semi Join相关

    Skew Join 真实数据中数据倾斜是一定的, hadoop 中默认是使用 hive.exec.reducers.bytes.per.reducer = 1000000000 也就是每个节点的red ...

  6. ORA-00933 UNION 与 ORDER BY

    原文:http://blog.csdn.net/lwei_998/article/details/6093807 The UNION operator returns only distinct ro ...

  7. 教你怎样在ppt2010抠图的小技巧|用ppt2010抠图的方法

    我们经常在ppt2010里做幻灯片时会碰到插入的图片并不是我们想要的情况,有的图片只是想要其中的一个部分.我们用“裁剪”功能也是达不到自己想要的效果.有的人会说PS抠图啊,但是比较繁琐,不易懂,不好上 ...

  8. UVa 10020 - Minimal coverage(区间覆盖并贪心)

    Given several segments of line (int the X axis) with coordinates [Li, Ri]. You are to choose the min ...

  9. UVa 129 Krypton Factor困难的串 (dfs 递归搜索)

    回溯法,只需要判断当前串的后缀,而不是所有的子串 #include<iostream> #include<cstdio> using namespace std; ]; int ...

  10. d038: 星罗密布

    内容: 输出图形 *****$***$$$*$$$$$ 规律是...自己发现吧. 要求输入3,输出上面三行的图形 输入说明: 行数小于40 输出说明:   输入样例:   3 输出样例 : ***** ...