Mybatis第一天

1、配置开发环境

  • jdk:1.8
  • mysql:8.0
  • maven:3.6.1
  • idea:2021.3

2、导入依赖和配置文件

  1. 在pom.xml中导入mybatis需要的依赖

    		<!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.27</version>
            </dependency>
    
            <!--mybatis-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.9</version>
            </dependency>
    
            <!--junit-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13.2</version>
                <scope>test</scope>
            </dependency>
    
  2. 配置mybatis的核心文件

    <!--在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>
    
        <!--配置mysql-->
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql://127.0.0.1:3306/langsin?characterEncoding=UTF-8&amp;useSSL=false&amp;useUnicode=true&amp;serverTimezone=Asia/Shanghai&amp;allowPublicKeyRetrieval=true&amp;rewriteBatchedStatements=true"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/>
                </dataSource>
            </environment>
        </environments>
    
        <!--注册接口的实现文件-->
        <mappers>
            <mapper resource="dao/UserMapper.xml"/>
        </mappers>
    </configuration>
    

    注释:配置文件中,关于mysql连接的driver、url、username、password写自己的

3、编写程序

  1. 创建生成sqlSession对象的工具类,sqlSession对象 ≈ Connection对象

    public class MybatisTools {
    
        //定义sqlSessionFactory实例
        private static SqlSessionFactory sqlSessionFactory;
    
        //加载配置文件,初始化sqlSessionFactory实例(建造者模式)
        static {
            try {
                String resource = "mybatis-config.xml";
                InputStream inputStream = Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        //生成执行SQL的sqlSession对象
        public static SqlSession getSqlSession(){
            return sqlSessionFactory.openSession();
        }
    }
    
  2. 创建实体类

    1.	Plugins中下载lombok插件
    2.	导入lombok依赖,能够使用注解自动生成构造器和一些object的方法
    
    		<!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.22</version>
                <scope>provided</scope>
            </dependency>
    
    @Data	//object全方法
    @NoArgsConstructor	//无参构造器
    @AllArgsConstructor	//全参构造器
    public class User {
        private Long userId;
        private String username;
        private String password;
        private String cname;
        private String gender;
        private Integer age;
        private String telephone;
        private String email;
        private String address;
        private Integer roleId;
        private String isLogin;
    }
    
  3. 创建UserMapper接口,= UserDao

    public interface UserMapper {
        List<User> queryUserList();
    }
    
  4. 创建UserMapper.xml文件,≈ UserDaoImpl

    <?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">
    <!--namespace跟接口关联-->
    <mapper namespace="dao.UserMapper">
     	<!--id跟接口中的方法关联-->
        <!--resultMap是返回值,这里可以用resultType,用map是为了跟表中各列的关联,能正确输出数据-->
        <select id="queryUserList" resultMap="userMap">
            select * from user
        </select>
        <resultMap id="userMap" type="pojo.User">
            <id column="user_id" property="userId"/>
            <result column="role_id" property="roleId"/>
            <result column="is_login" property="isLogin"/>
        </resultMap>
    </mapper>
    

4、测试

  1. 测试代码

    public class UserMapperTest {
        @Test
        public void test01(){
            //通过工具类获取sqlSession对象
            SqlSession sqlSession = MybatisTools.getSqlSession();
            //通过映射接口实现文件就能确定dao层有哪些方法
            //param:UserMapper的类对象
            //原因:在UserMapper.xml文件中已经绑定了接口,因此找类对象间接就找到了xml文件
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //调用方法,没什么说的
            List<User> list = mapper.queryUserList();
            for (User user : list) {
                System.out.println(user);
            }
            //关闭资源
            sqlSession.close();
        }
    }
    
  2. 测试结果

    User(userId=6, username=gousheng, password=123456, cname=张狗蛋, gender=男, age=33, telephone=15555555555, email=999, address=北京东城, roleId=1, isLogin=0)
    
    User(userId=10, username=jiadao, password=123456, cname=贾岛, gender=, age=35, telephone=, email=jiadao@baomidou.com, address=大唐长安街, roleId=3, isLogin=0)
    
    User(userId=11, username=wangwei, password=123213, cname=王维, gender=男, age=35, telephone=13647854785, email=wangwei@baomidou.com, address=大唐长安街44号, roleId=3, isLogin=0)
    
    User(userId=12, username=libai, password=123213, cname=李白, gender=男, age=35, telephone=138455625621, email=libai@baomidou.com, address=null, roleId=2, isLogin=0)
    
    User(userId=14, username=dufu, password=123213, cname=杜甫, gender=null, age=35, telephone=null, email=dufu@baomidou.com, address=null, roleId=2, isLogin=0)
    
    User(userId=15, username=zhangfei, password=123456, cname=杜牧, gender=男, age=24, telephone=13645674567, email=zhangfei@163.com, address=济南市趵突泉, roleId=2, isLogin=0)
    
    User(userId=1329378113234169858, username=menghaoran, password=123213, cname=孟浩然, gender=null, age=35, telephone=null, email=menghaoran@baomidou.com, address=null, roleId=2, isLogin=0)
    
    User(userId=1407985458301927426, username=hezhizhang, password=123456, cname=孟浩然, gender=null, age=22, telephone=13645784578, email=haoran@163.com, address=湖北襄阳, roleId=2, isLogin=0)
    
    User(userId=1407985458301927427, username=hezhizhang, password=123456, cname=孟浩然, gender=null, age=22, telephone=13645784578, email=haoran@163.com, address=湖北襄阳, roleId=2, isLogin=0)
    

5、总结

  1. 与jdbc开发的不同

    #1.jdbc中是获取Connection对象,mybatis是获取sqlSession对象
    
    #2.mybatis改用xml文件的方式来实现接口,实现了java代码和SQL语句解耦合
    
  2. 异常

    #1.异常一
    org.apache.ibatis.binding.BindingException: Type interface dao.UserMapper is not known to the MapperRegistry.
    意思:实现文件未注册
    解决:在mybatis核心配置文件中注册实现文件(后续可以通过包扫描解决,pojo也可以包扫描起别名。用了MP这些基本的SQL也不用写了)
    
    #2.异常二
    Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource dao/UserMapper.xml
    意思:在target下找不到xml文件(idea就是这样的)
    解决:在pom.xml中加入以下配置,然后使用maven命令clean清理target目录重新运行
    
    	<!--使得idea能够将java目录下的xml文件编译到target目录-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
            </resources>
        </build>
    
  3. mybatis使用步骤

    #1.导入相关依赖
    
    #2.书写mybatis-config.xml核心文件
    
    #3.创建mybatis工具类
    
    #4.创建UserMapper接口
    
    #5.书写UserMapper.xml实现文件
    
    #6.测试代码
    上述6步,在日后的使用中,只需改动其中4步即可
    2.核心文件中可能需要注册更多的实现文件
    4.接口中增加新方法,或者增加新接口
    5.实现文件中对于新方法要有对应的SQL语句
    6.测试代码也就是业务根据实际需求变化
    
上一篇:ACM/ICPC 大赛常见英语词汇


下一篇:学妹问,学网站开发还是打 ACM?