准备工作

  1. 将之前的项目复制一份,改名,然后将对应的pom文件中的

    改成新的项目名称
  1. 将新的项目导入到idea中,直接打开pom文件 一直点下一步即可
    注意:在编写测试方法时,测试类的名字为UserMapperTest,测试方法的方法名为testXxxx,这样取名符合编程规范

  2. 数据库:

    drop database if exists mybatisdemo;
    create  database mybatisdemo;
    use mybatisdemo;
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id`         int(11) NOT NULL AUTO_INCREMENT,
      `username`  varchar(32) NOT NULL COMMENT '用户名称',
      `birthday`  date DEFAULT NULL COMMENT '生日',
      `sex`       char(1) DEFAULT NULL COMMENT '性别',
      `address`   varchar(256) DEFAULT NULL COMMENT '地址',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
    INSERT INTO `user` VALUES ('1', '张三', '2018-07-10', '1', '北京');
    INSERT INTO `user` VALUES ('2', '李四', '2018-07-10', '0', '上海');
    INSERT INTO `user` VALUES ('3', '王五', '2018-07-10', '1', '广州');
    INSERT INTO `user` VALUES ('4', '王六', '2018-07-10', '1', '深圳');
    INSERT INTO `user` VALUES ('5', '王八', '2018-07-10', '1', '上海');

Mybatis 案例

案例1:返回单一实体对象

  • Mapper接口方法

    //     1.返回单一实体对象
         public User selectById(int id);
  • Mapper.xml

    <!--1.返回单一实体对象-->
       <select id="selectById" parameterType="_int" resultMap="baseResultMap">
            select  id, username ,birthday,sex , address from user where id = #{id}
        </select>
  • test方法

    //除了主体部分的代码 之后的案例将会省略
    public class MybatisTest {
        UserMapper userMapper = null;
        InputStream inputstream = null;
        SqlSession sqlSession = null;
        @Before
        public void before(){
            try {
                inputstream = Resources.getResourceAsStream("mybatis-config.xml");
                sqlSession = new SqlSessionFactoryBuilder().build(inputstream).openSession();
                userMapper = sqlSession.getMapper(UserMapper.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //     1.返回单一实体对象
        @Test
        public void testSelectById(){
            User user = userMapper.selectById(1);
            System.out.println(user);
        }
    //关闭资源
        @After
        public void after(){
            if(sqlSession!=null){
                sqlSession.close();
            }
            if(inputstream!=null){
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 运行结果

    DEBUG [main] - ==>  Preparing: select id, username ,birthday,sex , address from user where id = ? 
    DEBUG [main] - ==> Parameters: 1(Integer)
    TRACE [main] - <==    Columns: id, username, birthday, sex, address
    TRACE [main] - <==        Row: 1, 张三, 2018-07-10, 1, 北京
    DEBUG [main] - <==      Total: 1
    User{id=1, username='张三', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='北京'}

案例2:返回集合实体对象

  • Mapper接口方法

    //     2.返回集合实体对象
         public List<User> selectAllUser();
  • Mapper.xml

    <!--2.返回集合实体对象-->
         <select id="selectAllUser"  resultMap="baseResultMap">
            select  id, username ,birthday,sex , address from user
        </select>
  • test方法

    //除了主体部分的代码 之后的案例将会省略
        //     2.返回集合实体对象
        @Test
        public void testSelectAllUser(){
            List<User> users = userMapper.selectAllUser();
            for (User u :
                    users) {
                System.out.println(u);
            }
        }
  • 运行结果

    DEBUG [main] - ==>  Preparing: select id, username ,birthday,sex , address from user 
    DEBUG [main] - ==> Parameters: 
    TRACE [main] - <==    Columns: id, username, birthday, sex, address
    TRACE [main] - <==        Row: 1, 张三, 2018-07-10, 1, 北京
    TRACE [main] - <==        Row: 2, 李四, 2018-07-10, 0, 上海
    TRACE [main] - <==        Row: 3, 王五, 2018-07-10, 1, 广州
    TRACE [main] - <==        Row: 4, 王六, 2018-07-10, 1, 深圳
    TRACE [main] - <==        Row: 5, 王八, 2018-07-10, 1, 上海
    DEBUG [main] - <==      Total: 5
    User{id=1, username='张三', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='北京'}
    User{id=2, username='李四', birthday=Tue Jul 10 00:00:00 CST 2018, sex='0', address='上海'}
    User{id=3, username='王五', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='广州'}
    User{id=4, username='王六', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='深圳'}
    User{id=5, username='王八', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='上海'}

    以上的两个例子之前有相似的讲解,比较简单


案例3:返回Map形式的集合

  • Mapper接口方法

    //     3.返回Map形式的集合 
    //@MapKey确定了与User在Map中绑定的元素对象
        @MapKey("id")
        Map<Integer,User> selectAllMapUser();
  • Mapper.xml

    <!--3.返回Map形式的集合-->
        <select id="selectAllMapUser" resultMap="baseResultMap">
            select  id, username ,birthday,sex , address from user
        </select>
  • test方法
    返回为map的好处就是可以快速索引主键 此时的主键是id
    使用map的优势 如果用list 就得一个一个的遍历 但是如果使用map

    //     3.返回Map形式的集合
        @Test
        public void testSelectAllMapUser(){
            Map<Integer, User> userMap = userMapper.selectAllMapUser();
            //遍历map
            Set<Integer> keys = userMap.keySet();
            for(Integer key:keys){
                System.out.println(key+"-->" + userMap.get(key));
            }
    //example
            System.out.println("-----打印id为4的用户----");
            System.out.println("4"+"-->" + userMap.get(4));
            System.out.println("-----------------------");
    }
  • 运行结果

    DEBUG [main] - ==>  Preparing: select id, username ,birthday,sex , address from user 
    DEBUG [main] - ==> Parameters: 
    TRACE [main] - <==    Columns: id, username, birthday, sex, address
    TRACE [main] - <==        Row: 1, 张三, 2018-07-10, 1, 北京
    TRACE [main] - <==        Row: 2, 李四, 2018-07-10, 0, 上海
    TRACE [main] - <==        Row: 3, 王五, 2018-07-10, 1, 广州
    TRACE [main] - <==        Row: 4, 王六, 2018-07-10, 1, 深圳
    TRACE [main] - <==        Row: 5, 王八, 2018-07-10, 1, 上海
    DEBUG [main] - <==      Total: 5
    1-->User{id=1, username='张三', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='北京'}
    2-->User{id=2, username='李四', birthday=Tue Jul 10 00:00:00 CST 2018, sex='0', address='上海'}
    3-->User{id=3, username='王五', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='广州'}
    4-->User{id=4, username='王六', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='深圳'}
    5-->User{id=5, username='王八', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='上海'}
    -----打印id为4的用户----
    4-->User{id=4, username='王六', birthday=Tue Jul 10 00:00:00 CST 2018, sex='1', address='深圳'}
    -----------------------
    

案例4 :返回Map形式的数据行

  • Mapper接口方法
    //     4.返回Map形式的数据行
         List<Map<String,Object>>selectAllMapCol();
  • Mapper.xml
    <!--4.返回Map形式的数据行-->
        <select id="selectAllMapCol" resultType="map">
            select  id, username ,birthday,sex , address from user
        </select>
  • test方法
    //     4.返回Map形式的数据行
        /*原来的3方法,list 返回的是一个User对象
        *现在把每一行 返回为Map形式
        * 在resultType中写map或者HashMap都可以
        *
        */
        @Test
        public void testSelectAllMapCol(){
            List<Map<String, Object>> maps = userMapper.selectAllMapCol();
            for (Map<String, Object> map :
                    maps) {
                Set<String> cols = map.keySet();
                for (String col :
                        cols) {
                    System.out.print(col+":"+map.get(col)+"\t");
                }
                System.out.println();
            }
        }
  • 运行结果
    DEBUG [main] - ==>  Preparing: select id, username ,birthday,sex , address from user 
    DEBUG [main] - ==> Parameters: 
    TRACE [main] - <==    Columns: id, username, birthday, sex, address
    TRACE [main] - <==        Row: 1, 张三, 2018-07-10, 1, 北京
    TRACE [main] - <==        Row: 2, 李四, 2018-07-10, 0, 上海
    TRACE [main] - <==        Row: 3, 王五, 2018-07-10, 1, 广州
    TRACE [main] - <==        Row: 4, 王六, 2018-07-10, 1, 深圳
    TRACE [main] - <==        Row: 5, 王八, 2018-07-10, 1, 上海
    DEBUG [main] - <==      Total: 5
    birthday:2018-07-10	address:北京	sex:1	id:1	username:张三	
    birthday:2018-07-10	address:上海	sex:0	id:2	username:李四	
    birthday:2018-07-10	address:广州	sex:1	id:3	username:王五	
    birthday:2018-07-10	address:深圳	sex:1	id:4	username:王六	
    birthday:2018-07-10	address:上海	sex:1	id:5	username:王八