简介 MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apache software foundation 迁移到了google

code,并且改名为MyBatis。MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan
Old Java Objects,普通的Java对象)映射成数据库中的记录。

Mybatis的功能架构分为三层(图片借用了百度百科):

1)
API接口层:提供给外部使用的接口API,开发人员通过这些本地API来操纵数据库。接口层一接收到调用请求就会调用数据处理层来完成具体的数据处理。

2)
数据处理层:负责具体的SQL查找、SQL解析、SQL执行和执行结果映射处理等。它主要的目的是根据调用的请求完成一次数据库操作。

3)
基础支撑层:负责最基础的功能支撑,包括连接管理、事务管理、配置加载和缓存处理,这些都是共用的东西,将他们抽取出来作为最基础的组件。为上层的数据处理层提供最基础的支撑。

这里写图片描述

快速入门 这里写图片描述

Mybatis的整体流程图

jar包

mybatis.jar
mysql-connector-java.jar

conf.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>

    <properties resource="db.properties" />


    <!-- 别名设置,主要用在实体类的mapper.xml的实体类的resultType
    可以用typeAlias  然后type="对应类" alias="别名"
    或者定义一个 package 扫描所有 -->
    <typeAliases>
        <!-- <typeAlias type="com.coracle.mybatis.model.User" alias="User"/> <typeAlias 
            type="com.coracle.mybatis.model.Order" alias="Order"/> -->
        <!-- <package name="com.coracle.mybatis.model"/> -->
        <!-- <typeAlias type="com.corcle.mybatistest.entity.User" alias="User" /> -->
        <package name="com.corcle.mybatistest.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>


<!-- 注册 mapper.xml  如果是接口注解就用 class  或者 用package扫描所有接口
如果是xml  就要用 resuorce  一个 一个的注册 -->
    <mappers>
        <mapper resource="com/corcle/mybatistest/entity/userMapper.xml" />
        <!-- <mapper resource="com/coracle/mybatis/mapper/userMapper.xml"/> <mapper 
            resource="com/coracle/mybatis/mapper/userMapperCrud.xml"/> -->
        <!-- <mapper class="com.coracle.mybatis.intf.UserMapperCrud"/> -->
        <!-- <package name="com.coracle.mybatis.intf"/> -->
        <mapper class="com.corcle.mybatistest.service.UserService"/>
        <mapper resource="com/corcle/mybatistest/entity/classerInfoMapper.xml"/>
    </mappers>

</configuration>

entity

普通的javabean就行

xxxmapper.xml文件

classLoad加载conf.xml

private SqlSession session = null;

    @Before
    public void before() {
        String xml = "conf.xml";
        InputStream in = ClassTest.class.getClassLoader().getResourceAsStream(
                xml);
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in);
        session = sf.openSession();
    }

    @After
    public void close() {
        session.close();
    }

SqlSessionFactoryBuilder.build(inputStream)

SqlSession

记得 session 更新插入的 事务提交 session.commit();

获取sqlid

命名空间加 语句id

String statement = "com.corcle.mybatistest.entity.classerInfoMapper.getClass";
        List<ClassInfo> list = 

执行sql

session.selectList(statement);

别名typeAliases-》 typeAlias

别名主要是用在 mapper.xml中。 可以用package扫描所有,或者 一个 一个的设置

<typeAlias type="com.corcle.mybatistest.entity.User" alias="User" />
<package name="com.corcle.mybatistest.entity"/>

package 设置的默认的别名 是类名

<properties resource="db.properties" />

resultMap 视图模型–查询字段和pojo不对应

一对一(嵌套结果、嵌套查询-》循环查询)

/**
     * 嵌套结果 1-1查询
     */
    @Test
    public void oneToOneSelectTest() {
        String statement = "com.corcle.mybatistest.entity.classerInfoMapper.getClass";
        List<ClassInfo> list = session.selectList(statement);
        System.out.println(JSON.toJSON(list));
    }
运行结果
2016-03-18 14:49:09,836 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClass] - ==>  Preparing: select * from classinfo c inner join teacher t where c.t_id=t.t_id; 
2016-03-18 14:49:09,886 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClass] - ==> Parameters: 
2016-03-18 14:49:09,909 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClass] - <==      Total: 2
[{"teacher":{"tName":"lyh","tId":1},"cId":1,"cName":"一班"},{"teacher":{"tName":"djd","tId":2},"cId":2,"cName":"二班"}]
    /**
     * 嵌套查询 1-1查询
     */
    @Test
    public void oneToOneSelectTest2() {
        String statement = "com.corcle.mybatistest.entity.classerInfoMapper.getClassinfo";
        List<ClassInfo> list = session.selectList(statement);
        System.out.println(JSON.toJSON(list));
    }

运行结果
2016-03-18 14:50:25,992 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClassinfo] - ==>  Preparing: select * from classinfo; 
2016-03-18 14:50:26,039 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClassinfo] - ==> Parameters: 
2016-03-18 14:50:26,060 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - ====>  Preparing: select t_id tId,t_name tName from teacher where t_id=? 
2016-03-18 14:50:26,060 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - ====> Parameters: 1(Integer)
2016-03-18 14:50:26,061 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - <====      Total: 1
2016-03-18 14:50:26,061 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - ====>  Preparing: select t_id tId,t_name tName from teacher where t_id=? 
2016-03-18 14:50:26,061 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - ====> Parameters: 2(Integer)
2016-03-18 14:50:26,062 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getTeacher] - <====      Total: 1
2016-03-18 14:50:26,062 [main] DEBUG [com.corcle.mybatistest.entity.classerInfoMapper.getClassinfo] - <==      Total: 2
[{"teacher":{"tName":"lyh","tId":1},"cId":1,"cName":"一班"},{"teacher":{"tName":"djd","tId":2},"cId":2,"cName":"二班"}]

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.corcle.mybatistest.entity.classerInfoMapper">

    <resultMap type="ClassInfo" id="classinfo_map">
        <id column="c_id" property="cId"></id>
        <result column="c_name" property="cName" />
        <association property="teacher" javaType="Teacher">
            <id column="t_id" property="tId"></id>
            <result column="t_name" property="tName" />
        </association>
    </resultMap>

    <resultMap type="ClassInfo" id="classinfo_map_sel">
        <id column="c_id" property="cId"></id>
        <result column="c_name" property="cName" />
        <association property="teacher" column="t_id" select="getTeacher">
            <id column="t_id" property="tId"></id>
            <result column="t_name" property="tName" />
        </association>
    </resultMap>

    <select id="getTeacher" parameterType="int" resultType="Teacher">
        select
        t_id tId,t_name tName from teacher where t_id=#{id}
    </select>

    <select id="getClass" resultMap="classinfo_map">
        select * from classinfo c inner
        join teacher t where c.t_id=t.t_id;
    </select>


    <select id="getClassinfo" resultMap="classinfo_map_sel">
        select * from classinfo;
    </select>
</mapper>

一对多 collection (嵌套结果-嵌套查询)

嵌套查询

<select id="getclassallinfo" resultMap="getclassallinfomap">
        select * from student st inner join classinfo c on st.si_ci=c.c_id inner
        join teacher t on c.t_id =t.t_id
    </select>

    <resultMap type="ClassInfo" id="getclassallinfomap" extends="classinfo_map">
        <collection property="students" ofType="Student">
            <id column="st_id" property="stId"></id>
            <result column="st_name" property="stName" />
            <result column="si_ci" property="stCi" />
        </collection>
    </resultMap>

    <resultMap type="ClassInfo" id="classinfo_map">
        <id column="c_id" property="cId"></id>
        <result column="c_name" property="cName" />
        <association property="teacher" javaType="Teacher">
            <id column="t_id" property="tId"></id>
            <result column="t_name" property="tName" />
        </association>
    </resultMap>

注意 collection和 association 不同的是

collection 用 ofType 表示多的类型
association用 javaType来表示 1

/**
     * 嵌套结果 1-n查询
     */
    @Test
    public void oneToManySelectTest() {
        String statement = "com.corcle.mybatistest.entity.classerInfoMapper.getclassallinfo";
        List<ClassInfo> list = session.selectList(statement);
        System.out.println(JSON.toJSON(list));
    }

extends

resultMap 可以被继承!

分页(插件)

动态传入数据表参数

select * from ${tablename}

更少的创建实体类

可以省一些 vo(视图模型),但是就不规范了!
具体做法!–》
resultType 用 map

动态sql

批量插入 list

存储过程

事物

缓存

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐