MyBatis框架总结

MyBatis简介

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation
迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)

这里写图片描述

2.MyBatis是对JDBC技术做的封装。
封装了以下功能

  • 封装了获取连接、创建statement、设置sql参数、执行sql、释放连接过程
  • 封装了将查询结果ResultSet记录映射成实体对象过程
  • 封装了Dao对象实现过程(只提供接口,框架生成实现对象)

3.程序员使用MyBatis需要做以下工作:
这里写图片描述

  • 搭建MyBatis框架环境
  • 编写实体类
  • 编写SQL语句
  • 编写Dao接口
  • 获取SqlSession进行数据库操作

4.Mybatis基本应用
要求:对DEPT表进行增删改查操作。

1. 搭建MyBatis框架环境

    - 引入mybatis.jar和ojdbc.jar包
    - 添加SqlMapConfig.xml,设置数据库连接参数

            <configuration>
                <environments default="environment">
                    <environment id="environment">
                        <transactionManager type="JDBC" />
                        <dataSource type="POOLED">
                            <property name="driver" 
                                value="oracle.jdbc.OracleDriver" />
                            <property name="url"
                                value="jdbc:oracle:thin:@localhost:1521:XE"/>
                            <property name="username" value="SCOTT" />
                            <property name="password" value="TIGER" />
                        </dataSource>
                    </environment>
                </environments>
                <!-- 加载SQL定义文件 -->
                <mappers>
                    <mapper resource="cn/xdl/sql/DeptMapper.xml" />
                </mappers>
            </configuration> 

2. 编写实体类Dept

        public class Dept implements Serializable{

            private int deptno;
            private String dname;
            private String loc;

            public int getDeptno() {
                return deptno;
            }
            public void setDeptno(int deptno) {
                this.deptno = deptno;
            }
            //省略其他set/get方法

3. 编写SQL定义文件

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

         <!-- namespace指定和哪个接口映射 -->
        <mapper namespace="cn.xdl.dao.DeptMapper">

            <!-- resultType是select特有 -->
            <select id="findAll" resultType="cn.xdl.entity.Dept">
                select * from DEPT
            </select>

            <select id="findById" resultType="cn.xdl.entity.Dept" parameterType="int">
                select * from DEPT where DEPTNO=#{no}
            </select>

            <insert id="save" parameterType="cn.xdl.entity.Dept">
                insert into DEPT(DEPTNO,DNAME,LOC) values (#{deptno},#{dname},#{loc})
            </insert>

            <update id="update" parameterType="cn.xdl.entity.Dept">
                update DEPT set DNAME=#{dname},LOC=#{loc} where DEPTNO=#{deptno}
            </update>

            <!-- 如果parameterType为单个值,#{标识符}表达式标识符没有约定 -->
            <delete id="delete" parameterType="int">
                delete from DEPT where DEPTNO=#{id}
            </delete>

        </mapper>

SQL参数部分,可以使用${标识符}或#{标识符},如果使用#{}内部采用预编译机制执行SQL操作。如果使用${}内部采用非预编译过程。

4. 编写Mapper接口(Mapper映射器)

        /**
         * 方法定义参考SQL定义的id、parameterType、resultType属性
         * @author Administrator
         * 1.方法名与id属性一致
         * 2.参数类型与parameterType属性一致
         * 3.返回结果:多行查询List<resultType>;单行查询 resultType;增删改为void或int
         * 4.SQL定义文件中namespace="cn.xdl.dao.DeptMapper"
         */
        public interface DeptMapper {

            public List<Dept> findAll();

            public Dept findById(int id);

            public int save(Dept dept);

            public int update(Dept dept);

            public int delete(int id);

        }

5. 获取SqlSession操作

public class MyBatisUtil {

            public static SqlSession getSession() throws IOException{
        //      SqlSessionFactoryBuilder
                SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
                Reader reader = Resources.getResourceAsReader("sqlmap-config.xml");
        //      SqlSessionFactory
                SqlSessionFactory factory = builder.build(reader);
        //      SqlSession
                SqlSession session = factory.openSession();
                return session;
            }
        }

6. 利用SqlSession获取DeptMapper接口对象

@Test//按规则定义DeptMapper接口,由框架生成实现对象
            public void test1() throws IOException{
                SqlSession session = MyBatisUtil.getSession();
                //由框架生成DeptMapper接口实现对象
                DeptMapper deptDao = session.getMapper(DeptMapper.class);
                System.out.println(deptDao.getClass().getName());
                List<Dept> list = deptDao.findAll();
                for(Dept dept:list){
                    System.out.println(dept.getDeptno()+" "+dept.getDname()+" "+dept.getLoc());
                }
            session.close();
        }

Mybatis扩展操作

  1. 如果SQL参数#{}获取null值,会出现无效列类型:11111

解决方法:需要在#{key,jdbcType=类型},类型从下面表中选择

2. 为自定义类型指定别名

  • 在sqlmapconfig.xml中定义别名

<typeAliases> <typeAlias type="cn.xdl.entity.Dept"
alias="dept"/> </typeAliases>

  • 在SQL定义部分给parameterType或resultType属性使用dept

<select id="findAll" resultType="dept">
select * from DEPT </select>

3. 显示MyBatis底层SQL执行日志

在sqlmapconfig.xml中开启日志输出
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
  1. 分页查询

    • 下载pageHelper分页工具包
    • 在sqlmapconfig.xml中配置工具包
<plugins>
   <plugin  interceptor="com.github.pagehelper.PageHelper">
    <property name="dialect" value="oracle"/>
   </plugin>
</plugins>
- 分页代码

        PageHelper.startPage(2, 5);//分页查询设置,查询第2页,一页5条
        List<Dept> list = deptDao.findAll();

    使用sqlSession.selectList("sql的id",sql参数,RowBounds对象)

        RowBounds bound = new RowBounds(5,5);
        SqlSession session = MyBatisUtil.getSession();
        List<Dept> list = session.selectList("findAll", null, bound);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值