快速搭建 MyBatis

  1. Maven

     <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version> RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.2.8</version>
            </dependency>
         <!--日志约束-->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version> RELEASE</version>
            </dependency>
    
  2. mybatis-config.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>
        <!--配置别名-->
        <typeAliases>
            <package name="com.sf.wj.domain"/>
        </typeAliases>
        <!--数据源配置-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"></transactionManager>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/company?serverTimezone=UTC"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
        
        <!--资源引用-->
        <mappers>
            <mapper resource="mappers/UserMapper.xml"/>
        </mappers>
    
    </configuration>
    
  3. 【测试类 - 部分】根据 xml 配置文件(全局配置文件) 创建一个 SqlSessionFactory 对象

    package com.sf.wj;
    
    import com.sf.wj.domain.User;
    import com.sf.wj.mapper.UserMapper;
    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.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class UserTest {
        private UserMapper mapper;
        private SqlSession sqlSession;
        private InputStream inputStream;
        @Before
        public void setUp() throws IOException {
            String rusource = "mybatis-config.xml";
             inputStream = Resources.getResourceAsStream(rusource);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //默认传入参数false,不自动提交
            sqlSession = factory.openSession(false); // 2、获取sqlSession实例,能直接执行已经映射的 sql 语句
            mapper = sqlSession.getMapper(UserMapper.class);
        }
    
       
    
  4. 创建 mapper 映射

    <?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.sf.wj.mapper.UserMapper"><!-- namespace:名称空间 -->
        <select id="queryById" parameterType="int" resultType="User"><!--id:唯一表示、resultType:返回值类型-->
            select * from user where id = #{id}<!--#{id}接口从传递过来的参数-->
        </select>
    
        <delete id="deleteById" parameterType="Integer" >
            delete from user where id = #{id}
        </delete>
    
        <select id="queryAll" resultType="User">
            select * from user
        </select>
    
        <update id="updateUser" parameterType="User">
            update user set username = #{username},password = #{password} where id=#{id}
        </update>
    
        <insert id="insertUser" parameterType="User">
            insert into user (id,username,password) values (#{id},#{username},#{password})
        </insert>
      
      <!--按多个id查找用户 foreach-->
      <select id="queryByIds" resultType="User">
          select * from user where id in
          <foreach collection="array" open="(" close=")" separator="," item="id">
            #{id}
          </foreach>
      </select>
    </mapper>
    
  5. 创建 mapper 接口

    package com.sf.wj.mapper;
    
    import com.sf.wj.domain.User;
    
    import java.util.List;
    
    public interface UserMapper {
        User queryById(int id);
        void deleteById(int id);
        List<User> queryAll();
        void  updateUser(User user);
        void insertUser(User user);
        List<User> queryByIds(int[] ids);
    }
    
    
  6. 补完测试类

    package com.sf.wj;
    
    import com.sf.wj.domain.User;
    import com.sf.wj.mapper.UserMapper;
    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.After;
    import org.junit.Before;
    import org.junit.Test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    public class UserTest {
        private UserMapper mapper;
        private SqlSession sqlSession;
        private InputStream inputStream;
        @Before
        public void setUp() throws IOException {
            String rusource = "mybatis-config.xml";
             inputStream = Resources.getResourceAsStream(rusource);
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
            //默认传入参数false,不自动提交
            sqlSession = factory.openSession(false); // 2、获取sqlSession实例,能直接执行已经映射的 sql 语句
            mapper = sqlSession.getMapper(UserMapper.class);
        }
    
        @After
        public void commit(){
            try {
                sqlSession.commit();
                inputStream.close();
                sqlSession.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Test
        public void queryByIdTest(){
            User user = mapper.queryById(1);
            System.out.println(user);
        }
        @Test
        public void queryAllTest(){
            List<User> user = mapper.queryAll();
            System.out.println(user);
        }
        @Test
        public void deleteTest(){
            mapper.deleteById(1);
        }
        @Test
        public void updateTest(){
            User user=new User();
            user.setId(1);
            user.setPassword("qwert");
            user.setUsername("jg");
            mapper.updateUser(user);
        }
    
        @Test
        public void insertTest(){
            User user=new User();
            user.setId(3);
            user.setPassword("369");
            user.setUsername("zs");
            mapper.insertUser(user);
        }
    
      //多个id查找
      @Test
      public void queryByIdsTest(){
          List<User> list = mapper.queryByIds(new int[]{1, 2, 3});
          System.out.println(list);
      }
    }
    

技术对比

# JDBC工具?Hibernate?

JDBC工具(Dbutils、jdbcTemplate…)缺点

  • sql语句在java 代码里面,硬编码,高耦合
  • 缺少整体的解决方案

Hibernate缺点

  • 无法优化 sql
  • 自定义 sql 需要学习 HQL (但框架旨在消除sql - 与宗旨矛盾)

# Mybatis

  • sql 与 java 编码分离
  • sql 开发人员控制

使用 Mybatis , 只要掌握好 sql 语句

半自动

历史