• 第一个Mybatis程序


    作者:进击攻城狮
    个人主页:欢迎访问我的主页
    首发时间:2022年8月12日星期五
    订阅专栏:Mybatis
    个人信条:星光不问赶路人,岁月不负有心人。
    注:当做笔记回顾,如果文章有错误,欢迎在评论区指正。
    🎉 支持我:点赞👍+收藏⭐️+留言📝​

    活动地址:CSDN21天学习挑战赛

    在这里插入图片描述
    在这里插入图片描述

    2、第一个Mybatis程序

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

    2.1、搭建环境

    搭建数据库

    CREATE DATABASE `mybatis`;
    
    USE `mybatis`;
    
    CREATE TABLE `user`(
      `id` INT(20) NOT NULL PRIMARY KEY,
      `name` VARCHAR(30) DEFAULT NULL,
      `pwd` VARCHAR(30) DEFAULT NULL
    )ENGINE=INNODB DEFAULT CHARSET=utf8;
    
    INSERT INTO `user`(`id`,`name`,`pwd`) VALUES 
    (1,'java','123456'),
    (2,'c++','123456'),
    (3,'c','123890')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    新建项目

    1. 新建一个普通的maven项目

    2. 删除src目录

    3. 导入maven依赖

          
          <dependencies>
              
              <dependency>
                  <groupId>mysqlgroupId>
                  <artifactId>mysql-connector-javaartifactId>
                  <version>5.1.47version>
              dependency>
              
              
              <dependency>
                  <groupId>org.mybatisgroupId>
                  <artifactId>mybatisartifactId>
                  <version>3.5.2version>
              dependency>
              
              <dependency>
                  <groupId>junitgroupId>
                  <artifactId>junitartifactId>
                  <version>4.12version>
              dependency>
          dependencies>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22

    2.2、创建一个模块

    • 编写mybatis的核心配置文件

      
      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=true&useUnicode=true&characterEncoding=UTF-8"/>
                      <property name="username" value="root"/>
                      <property name="password" value="123456"/>
                  dataSource>
              environment>
          environments>
      
      configuration>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
    • 编写mybatis工具类

      //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
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24

    2.3、编写代码

    • 实体类

      package com.kuang.pojo;
      
      //实体类
      public class User {
          private int id;
          private String name;
          private String pwd;
      
          public User() {
          }
      
          public User(int id, String name, String pwd) {
              this.id = id;
              this.name = name;
              this.pwd = pwd;
          }
      
          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 getPwd() {
              return pwd;
          }
      
          public void setPwd(String pwd) {
              this.pwd = pwd;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "id=" + id +
                      ", name='" + name + '\'' +
                      ", pwd='" + pwd + '\'' +
                      '}';
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
    • Dao接口

      public interface UserMapper {
          //获取全部用户
          List<User> getUserList();
      
          //根据ID查询用户
          User getUserById(int id);
      
          //插入用户
          int addUser(User user);
      
          //修改用户
          int updateUser(User user);
      
          //删除用户
          int deleteUser(int id);
      
          int addUser1(Map<String,Object> map);
      
          List<User>  getUserLike(String value);
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • 接口实现类由原来的UserDaoImpl转变为一个 Mapper配置文件.

      
      DOCTYPE mapper
              PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
              "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
          <mapper namespace="com.kuang.dao.UserMapper">
      
          <select id="getUserList" resultType="com.kuang.pojo.User">
              select * from mybatis.user1
          select>
      
          <select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
              select * from mybatis.user1 where id=#{id}
          select>
      
          <select id="getUserById2" parameterType="map" resultType="com.kuang.pojo.User">
              select * from mybatis.user1 where id=#{id} and name=#{name};
          select>
      
          <insert id="addUser" parameterType="com.kuang.pojo.User">
              insert into mybatis.user1 (id,name,pwd)value (#{id},#{name},#{pwd});
          insert>
      
          <update id="updateUser" parameterType="com.kuang.pojo.User">
              update mybatis.user1 set name=#{name},pwd=#{pwd} where id=#{id};
          update>
      
          <delete id="deleteUser" parameterType="com.kuang.pojo.User">
              delete  from mybatis.user1  where id=#{id};
          delete>
      
          <insert id="addUser1" parameterType="map">
              insert into mybatis.user1 (id,name,pwd) value (#{userid},#{userName},#{password});
          insert>
      
          <select id="getUserLike" resultType="com.kuang.pojo.User">
              select * from mybatis.user1  where name like "%"#{value}"%"
          select>
      
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39

    2.4、测试

    注意点:

    org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

    MapperRegistry是什么?

    核心配置文件中注册 mappers

    • junit测试

      public class UserDaoTest {
      
          @Test
          public void test() {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
      
              try {
                  //方式一
      //        UserDao mapper = sqlSession.getMapper(UserDao.class);
      //        List userList = mapper.getUserList();
      
                  //方式二
                  List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserList");
      
                  for (User user : userList) {
                      System.out.println(user);
                  }
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  sqlSession.close();
              }
      
      
              //sqlSession.close();
          }
      
      
          @Test
          public void getUserById() {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      
              User user = mapper.getUserById(1);
              System.out.println(user);
              sqlSession.close();
          }
      
          @Test
          public void addUser() {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      
              int res = mapper.addUser(new User(3, "一年", "123489"));
              if (res > 0) {
                  System.out.println("插入成功!~~~");
              }
              sqlSession.commit();
              sqlSession.close();
          }
      
          @Test
          public void updateUser()
          {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              mapper.updateUser(new User(2,"守望","157489"));
              sqlSession.commit();
              sqlSession.close();
          }
      
          @Test
          public void deleteUser()
          {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      
              mapper.deleteUser(1);
      
              sqlSession.commit();
              sqlSession.close();
      
          }
      
          public void addUser2()
          {
              SqlSession sqlSession=MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              HashMap<String, Object> Map = new HashMap<>();
      
              Map.put("user",5);
              Map.put("password","23333");
              mapper.addUser1(Map);
          }
      
          @Test
          public void getUserById2()
          {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              HashMap<String, Object> map = new HashMap<>();
              map.put("helloid",1);
              mapper.addUser1(map);
              sqlSession.close();
          }
      
      @Test
          public void getUserLike()
          {
              SqlSession sqlSession = MybatisUtils.getSqlSession();
              UserMapper mapper = sqlSession.getMapper(UserMapper.class);
              List<User> userLike = mapper.getUserLike("%守%");
      
              for (User user :
                      userLike) {
                  System.out.println(user);
              }
              sqlSession.commit();
              sqlSession.close();
          }
      }
      
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
      • 98
      • 99
      • 100
      • 101
      • 102
      • 103
      • 104
      • 105
      • 106
      • 107
      • 108
      • 109
      • 110
      • 111
      • 112

    可能会遇到的问题:

    1. 配置文件没有注册
    2. 绑定接口错误。
    3. 方法名不对
    4. 返回类型不对
    5. Maven导出资源问题
  • 相关阅读:
    C/C++:双重循环中的break
    设计模式笔记1
    盘点Win前端开发下常用的软件
    nuScenes数据集浅探(待完善……)
    RefConv: 重参数化的重新聚焦卷积(论文翻译)
    【重拾C语言】六、批量数据组织(四)线性表—栈和队列
    深度学习从入门到入土
    SQL Server教程 - T-SQL-编程基础
    分类预测 | MATLAB实现WOA-CNN-GRU-Attention数据分类预测
    Java实现DXF文件转换成PDF
  • 原文地址:https://blog.csdn.net/yi_chen_c/article/details/126313222