mybatis入门demo


  1. mysql创建user表
    CREATE TABLE `user`  (
      `id` int(32) NOT NULL COMMENT 'id\r\n',
      `name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `sex` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
      `birthday` date NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    SET FOREIGN_KEY_CHECKS = 1;
  2. 创建maven普通工程mybatis-parent,删除src目录,添加mybatis依赖。

    
        <dependencies>
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>5.1.47version>
            dependency>
            <dependency>
                <groupId>org.mybatisgroupId>
                <artifactId>mybatisartifactId>
                <version>3.5.3version>
            dependency>
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
            dependency>
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>1.2.17version>
            dependency>
        dependencies>
  3. 创建子模块mybatis-01
  4. resources目录下创建配置文件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>
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                dataSource>
            environment>
        environments>
        <mappers>
            <mapper resource="com/qiaob/mapper/UserMapper.xml"/>
        mappers>
    configuration>
  5. 封装mybatis工具类
    package com.qiaob.utils;
    
    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 java.io.IOException;
    import java.io.InputStream;
    
    public class MybatisUtils {
        static {
            //使用mybatis第一步:获取sqlSessionFactory对象
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = null;
                inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        private static SqlSessionFactory sqlSessionFactory;
    
        public static SqlSession getSqlSession() {
            return sqlSessionFactory.openSession();
        }
    
    
    }
  6. 生成pojo实体类
    package com.qiaob.pojo;
    
    import java.util.Date;
    
    public class User {
        private int id;
        private String name;
        private String sex;
        private Date birthday;
    
        public User() {
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    ", birthday=" + birthday +
                    '}';
        }
    
        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 String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    }
  7. 生成mapper数据层接口
    package com.qiaob.mapper;

    import com.qiaob.pojo.User;

    import java.util.ArrayList;

    public interface UserMapper {
    //查询所有
    public ArrayList getUserList();

    //根据id查询某个
    public User getUserById(int id);


    //插入用户
    public int addUser(User user);

    //更新用户
    public int updateUser(User user);

    //删除用户
    public int deleteUser(int id);

    }

8.  在resources相同层级目录下创建UserMapper.xml

:代表实现哪个mapper的接口方法
id="getUserList" :对应mapper的方法名

resultType="com.qiaob.pojo.User":对应返回集类型
parameterType="com.qiaob.pojo.User":sql中可以直接调用属性
sqlSession.commit():mybatis要手工提交事务才生效


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







insert into mybatis.user(id, name, sex, birthday) values (#{id},#{name},#{sex},#{birthday})


update mybatis.user set birthday = #{birthday} where id=#{id};


delete from mybatis.user where id =#{id}



9.创建单元测试类
  • 获得指定日期的方法
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d =null;
        try {
             d = sdf.parse("2018-03-09");
        } catch (ParseException e) {
            e.printStackTrace();
        }


package com.qiaob.dao;

import com.qiaob.mapper.UserMapper;
import com.qiaob.pojo.User;
import com.qiaob.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class UserDaoTest {
    @Test
    public void testUserList(){
        //第一步:获得sqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //第二步:执行sql
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        ArrayList userList = mapper.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }

        //第三步:关闭sqlSession
        sqlSession.close();
    }


    @Test
    public  void testGetUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }

    @Test
    public  void testSaveUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = new User(3, "乔逸之", "1", new Date());
        int num = mapper.addUser(user);

        System.out.println(num);

        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void testUpdate(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d =null;
        try {
             d = sdf.parse("2018-03-09");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        mapper.updateUser(new User(3,"乔逸之","1",d));

        sqlSession.commit();
        sqlSession.close();
    }


    @Test
    public void testDeleteUser( ){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser(3);
        sqlSession.commit();
        sqlSession.close();
    }

}

 补充:如果想将mapper.xml和mapper放在同一路径下,则需要在pom文件中增加导出过滤,见博客《》。