关于mybatis:Mybatis程序入门案例

28次阅读

共计 3719 个字符,预计需要花费 10 分钟才能阅读完成。

思路:搭建环境 —> 导入 Mybatis—> 编写代码 —> 测试

1.1、搭建环境

搭建数据库

create databases if not exists `mybatis`;

use `mybatis`;

create table if not exists `user`(`id` int(20) not null,
    `name` varchar(30) default null,
    `pwd` varchar(30) default null,
    primary key(`id`)
)engine=innodb default charset=utf8;

插入数据

insert into `user`(`id`,`name`,`pwd`) values
(1,'孙悟空','123456'),
(2,'猪八戒','111222'),
(3,'唐僧','789456');

新建我的项目
1. 新建一个一般的 maven 我的项目
2. 删除 src 目录
3. 导入 maven 依赖

<dependencies>
    <!--mysql 驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    
    <!--mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    
    <!--junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
<!-- 在 build 中配置 resources,来避免咱们资源导出失败的问题 -->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

1.2、创立一个模块

  • 编写 Mybaris 的外围配置文件

    <?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 外围配置文件 -->
    <configuration>
    <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://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai"/>
          <property name="username" value="root"/>
          <property name="password" value="root"/>
        </dataSource>
      </environment>
    </environments>
    <mappers>
      <mapper resource="com/jialidun/dao/UserMapper/xml"/>
    </mappers>
    </configuration>
  • 编写 mybatis 工具类

    package com.jialidun.utils;
    
    //sqlSessionFactory--->sqlSession
    public class MybatisUtils{
    
      private static SqlSessionFactory sqlSessionFactory;
      static{
      try{
          // 应用 mybatis 第一步:获取 sqlSessionFactory 对象
          String resource = "mybatis-config.xml";
          InputStream inputStream = Resources.getResourceAsStream(resource);
          sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          }catch(IOException e){e.printStackTrace();
          }
      }
    // 既然有了 SqlSessionFactory,顾名思义,咱们能够从中取得 SqlSession 的实例。//SqlSession 提供了在数据库执行 SQL 命令所需的所有办法。public static SqlSession getSqlSession(){return sqlSessionFactory.openSession();
      }
    }

    1.3、编写代码

  • 实体类

    package com.jialidun.pojo;
    
    @Data
    public class User{
      private int id;
      private String name;
      private String pwd;
    }
  • Dao 接口

    package com.jialidun.dao;
    
    public interface UserDao{List<User> getUserList();
    
    }
  • 接口实现类由原来的 UserDaoImpl 转变为一个 Mapper 配置文件
    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">
    <!--namespace= 绑定一个对应的 Dao/Mapper 接口 -->
    <mapper namespace="com.jialidun.dao.UserDao">
    
     <!--select 查问语句 -->
    <select id="getUserList" resultType="com.jialidun.pojo.User">
      select * from mybatis.user
    </select>
    </mapper>

    1.4、测试

    留神点:
    org.apache.ibatis.binding.BindingException:Type interface com.jialidun.dao.UserDao is not know to the MapperRegistry.

    package com.jialidun.dao;
    
    public class UserDaoTest{
      @Test
      public void test(){
          
          // 第一步:取得 SqlSession 对象
          SqlSession sqlSession = MybatisUtils.getSqlSession();
          
          try{UserDao userDao= sqlSession.getMapper(UserDao.class);
          List<User> userList = userDao.getUserList();
          
          // 形式二://List<User> userList = sqlSession.selectList("com.jialidun.dao.UserDao.getUserList");
          for(User user:userList){System.out.println(user);
          }
          }catch(Exception e){e.printStackTrace();
          }finally{
              // 敞开 SqlSession
              sqlSession.close();}
      
          
      }
    }

    可能遇到的问题:
    1. 配置文件没有注册
    2. 绑定接口谬误
    3. 办法名不对
    4. 返回类型不对
    5.Maven 导出资源问题

正文完
 0