Mybatis学习总结

来源:互联网 发布:淘宝主营占比在哪里看 编辑:程序博客网 时间:2024/04/24 19:47

一、理解什么是MyBatis?

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

  1)MyBATIS 目前提供了三种语言实现的版本,包括:Java、.NET以及Ruby。(我主要学习java,就讲java的使用)
  2)它提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。
  3)mybatis与hibernate的对比?

   mybatis提供一种“半自动化”的ORM实现。
   这里的“半自动化”,是相对Hibernate等提供了全面的数据库封装机制的“全自动化”ORM实现而言,“全自动”ORM实现了POJO和数据库表之间的映射,以及 SQL 的自动生成和执行。

    而mybatis的着力点,则在于POJO与SQL之间的映射关系。

二、mybatis入门基础

2.1创建项目环境,创建普通的jav项目或者javaweb项目都可以,如下图:

2.2添加相应的jar包

【mybatis包】


【MYSQL驱动包】
    mysql-connector-java-5.1.7-bin.jar
2.3创建数据库



2.4在src目录下创建Mybatis的配置文件SqlMapConfig.xml

SqlMapConfig.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">        <!-- 使用jdbc事务管理,事务控制由mybatis管理-->            <transactionManager type="JDBC" />        <!-- 数据库连接池,由mybatis管理-->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />                <property name="username" value="root" />                <property name="password" value="root" />            </dataSource>        </environment>    </environments><!-- 加载映射文件 -->    <mappers>        <mapper resource="com/mybatis/mapping/userMapper.xml"/>    </mappers></configuration>
2.5定义实体类,如下图:

User类的代码如下:

package com.mybatis.entity;/** * @author shi */public class User {private int id;private String name;private int age;public User() {}    public User(int id,String name,int age) {this.id=id;this.name=name;this.age=age;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}        public String  toString() {return "User[id="+id+",name="+name+",age="+age+"]";}}
2.6定义操作users类的sql映射文件userMapper.xml

userMapper.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,namespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的例如namespace="me.gacl.mapping.userMapper"就是me.gacl.mapping(包名)+userMapper(userMapper.xml文件去除后缀) --><mapper namespace="com.mybatis.mapping.userMapper">    <!-- 在select标签中编写查询的SQL语句, 设置select标签的id属性为getUser,id属性值必须是唯一的,不能够重复           使用parameterType属性指明查询时使用的参数类型,resultType属性指明查询返回的结果集类型    resultType="me.gacl.domain.User"就表示将查询结果封装成一个User类的对象返回    User类就是users表所对应的实体类    -->    <!--            根据id查询得到一个user对象    -->     <!-- 在映射文件中配置很多sql语句 -->     <!-- 需求:通过Id查询用户表的记录 -->     <!-- 通过SELECT执行数据库查询      id:标识映射文件中的sql,称为statement的id;              将sql语句封装在mapperStatement的对象中,所以Id称为Statement的id;     parameterType:指定输入参数的类型,这里指定int型    #{}:表示一个占位符;    #{id}:其中Id表示接收输入的参数,参数名称就是Id,如果输入参数是简单类型,#{}中的参数名可以任意,可以是value或者其它名称;    resultType:指定sql输出结果所映射的java对象类型,select指定resultType表示将单条记录映射成java对象。    -->    <select id="findUserById" parameterType="int"         resultType="com.mybatis.entity.User">        select * from users where id=#{id}    </select>    <!-- 根据用户名称模糊查询用户信息,可能返回多条数据    resultType:指定的就是单条记录所映射的java类型;    ${}:表示拼接sql字符串,将接收到的参数内容不加任何修饰拼接在sql中.          使用${}拼接sql,可能会引起sql注入    ${value}:接收输入参数的内容,如果传入的是简单类型,${}中只能使用value    -->    <select id="findUserByName" parameterType="java.lang.String"        resultType="com.mybatis.entity.User">        select * from users where name like '%${value}%'    </select>    <!-- 添加用户     parameterType:指定输入的参数类型是pojo(包括用户信息);    #{}中指定pojo的属性名称,接收到pojo对象的属性值    ,mybatis通过OGNL(类似struts2的OGNL)获取对象的属性值    -->    <insert id="insertUser" parameterType="com.mybatis.entity.User">        <!--                       将insert插入的数据的主键返回到User对象中;        select last_insert_id():得到刚insert进去记录的主键值,只适用于自增主键;        keyProperty:将查询到的主键值,设置到parameterType指定的对象的那个属性        order:select last_insert_id()执行顺序,相对于insert语句来说它的执行顺序。        resultType:指定select last_insert_id()的结果类型;        -->        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">            select last_insert_id()        </selectKey>        insert into users (name,age) values (#{name},#{age})    </insert>    <!-- 删除用户              根据ID删除用户,需要输入Id的值 -->     <delete id="deleteUser" parameterType="java.lang.Integer">         delete from users where id=#{id}     </delete>         <!-- 更新用户                   需要传入用户的Id和用户的更新信息       parameterType:指定User对象,包括Id和用户的更新信息,注意:Id是必须存在的       #{id}:从输入的user对象中获取Id的属性值 -->        <update id="updateUser" parameterType="com.mybatis.entity.User">           update users set name=#{name},age=#{age} where id=#{id}       </update>    </mapper>2.7在SqlMapConfig.xml文件中注册userMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 和spring整合后 environments配置将废除-->    <environments default="development">        <environment id="development">        <!-- 使用jdbc事务管理,事务控制由mybatis管理-->            <transactionManager type="JDBC" />        <!-- 数据库连接池,由mybatis管理-->            <dataSource type="POOLED">                <property name="driver" value="com.mysql.jdbc.Driver" />                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />                <property name="username" value="root" />                <property name="password" value="root" />            </dataSource>        </environment>    </environments><!-- 加载映射文件 -->    <mappers>        <mapper resource="com/mybatis/mapping/userMapper.xml"/>    </mappers></configuration>
2.8、编写测试代码:执行定义的select语句

  创建一个MybatisService类,编写如下的测试代码:

MybatisService源代码如下:

package com.mybatis.test;import java.io.IOException;import java.io.InputStream;import java.util.Date;import java.util.List;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test;import com.mybatis.entity.User;/** * @ClassName: MybatisService * @Description: TODO(mybatis入门程序) * @author warcaft * @date 2015-6-27 下午4:49:49 *  */public class MybatisService {    // 根据Id查询用户信息,得到一条记录结果    @Test    public void findUserByIdTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.创建会话工场,传入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通过工厂得到SqlSession            sqlSession = sqlSessionFactory.openSession();            // 3.通过sqlSession操作数据库            // 第一个参数:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数;            // sqlSession.selectOne结果是与映射文件所匹配的resultType类型的对象;            // selectOne:查询一条结果            User user = sqlSession.selectOne("com.mybatis.mapping.userMapper.findUserById", 4);            System.out.println(user.toString());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    // 根据姓名模糊查询用户信息,得到一条或多条记录结果    @Test    public void findUserByNameTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.创建会话工场,传入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通过工厂得到SqlSession            sqlSession = sqlSessionFactory.openSession();            // 3.通过sqlSession操作数据库            // 第一个参数:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数;            // sqlSession.selectOne结果是与映射文件所匹配的resultType类型的对象;            // list中的user和resultType类型一致            List<User> list = sqlSession.selectList("com.mybatis.mapping.userMapper.findUserByName", "王");            System.out.println(list);        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    // 添加用户    @Test    public void insertUserTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.创建会话工场,传入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通过工厂得到SqlSession            sqlSession = sqlSessionFactory.openSession();            //插入用户的对象            User user = new User();            user.setName("陈诗123");            user.setAge(100);            // 3.通过sqlSession操作数据库            // 第一个参数:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数;            // sqlSession.selectOne结果是与映射文件所匹配的resultType类型的对象;            sqlSession.insert("com.mybatis.mapping.userMapper.insertUser", user);            //执行提交事务            sqlSession.commit();                        //项目中经常需要 获取新增的用户的主键            System.out.println(user.getId());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }        // 根据Id删除用户        @Test        public void deleteUserTest() {            // mybatis的配置文件            String resource = "SqlMapConfig.xml";            InputStream inputStream = null;            SqlSession sqlSession = null;            try {                inputStream = Resources.getResourceAsStream(resource);                // 1.创建会话工场,传入mybatis的配置文件信息                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);                // 2.通过工厂得到SqlSession                sqlSession = sqlSessionFactory.openSession();                // 3.通过sqlSession操作数据库                // 第一个参数:映射文件中的statement的Id,等于namespace + "." + statement的id;                // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数;                // sqlSession.selectOne结果是与映射文件所匹配的resultType类型的对象;                //传入Id,删除用户                sqlSession.delete("com.mybatis.mapping.userMapper.deleteUser", 5);                //执行提交事务                sqlSession.commit();            } catch (IOException e) {                e.printStackTrace();            } finally {                if (sqlSession != null) {                    sqlSession.close();                }                if (inputStream != null) {                    try {                        inputStream.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }                // 根据Id更新用户信息        @Test        public void updateUserTest() {            // mybatis的配置文件            String resource = "SqlMapConfig.xml";            InputStream inputStream = null;            SqlSession sqlSession = null;            try {                inputStream = Resources.getResourceAsStream(resource);                // 1.创建会话工场,传入mybatis的配置文件信息                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);                // 2.通过工厂得到SqlSession                sqlSession = sqlSessionFactory.openSession();                //更新用户的信息                User user = new User();                user.setId(2);                user.setName("陈总");                user.setAge(23);                // 3.通过sqlSession操作数据库                // 第一个参数:映射文件中的statement的Id,等于namespace + "." + statement的id;                // 第二个参数:指定和映射文件中所匹配的parameterType类型的参数;                // sqlSession.selectOne结果是与映射文件所匹配的resultType类型的对象;                //更具Id更新用户                sqlSession.update("com.mybatis.mapping.userMapper.updateUser", user);                //执行提交事务                sqlSession.commit();            } catch (IOException e) {                e.printStackTrace();            } finally {                if (sqlSession != null) {                    sqlSession.close();                }                if (inputStream != null) {                    try {                        inputStream.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }}

2.9根据Id查询用户信息,得到一条记录结果,运行得到结果:


2.10根据姓名模糊查询用户信息,得到一条或多条记录结果如下:


2.11添加用户



                                             
1 0