思路:搭建环境--->导入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();
      //根据id查询用户
      User getUserById(int id);
      //insert 一个用户
      int addUser(User user);
      //修改用户
      int updateUser(User user);
      //删除用户
      int deleteUser(int id);
    
    }
  • 接口实现类由原来的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>
    
    <select id="getUserById" parameterType="int" resultType="com.jialidun.pojo.User">
      select * from mybatis.user where id = #{id}
    </select>
    
    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser" parameterType="com.jialidun.pojo.User">
       insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>
    
    <update id="updateUser" parameterType="com.jialidun.pojo.User">
         update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
    </update>
    
    <delete id="deleteUser" parameterType="int">
       delete from mybatis.user where id=#{id};
    
    </delete>
    
    </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();
          }
      
          
      }
      
      @Test
      public void getUserById(){
         
         SqlSession sqlSession = MybatisUtils.getSqlSession();
         
         UserMapper mapper = sqlSession.getMapper(UserDao.class);
         
        User user = mapper.getUserById(1);
         System.out,println(user);
         sqlSession.close();
      
      
      }
      
      @Test
      public void addUser(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
         
         UserMapper mapper = sqlSession.getMapper(UserDao.class);
         
        int num = mapper.addUser(4,"沙和尚","444555");
         if(num>0){
           System.out.println("添加用户成功!");
         
         }
         
         //提交事务
         sqlSession.commit();
         sqlSession.close();
      
      }
      
      @Test
      public void updateUser(){
         SqlSession sqlSession = MybatisUtils.getSqlSession();
         
         UserMapper mapper = sqlSession.getMapper(UserDao.class);
         
        mapper.updateUser(new User(4,"悟净","666666"));
         //提交事务
         sqlSession.commit();
         sqlSession.close();
      
      }
      
      @Test
      public void deleteUser(){
         SqlSession sqlSession = MybatisUtils.getSqlSession();
         
         UserMapper mapper = sqlSession.getMapper(UserDao.class);
         
        mapper.deleteUser(4);
        
        //提交事务
        sqlSession.commit();
        
         sqlSession.close();
      
      
      }
    }

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

    2、Mtbatis的CRUD操作

    2.1、namespace

    namespace中的包名要和Dao/mapper接口的包名一致!

    2.2、select

    选择,查询语句

  • id:就是对应的namespace中的方法名;
  • resultType:sql语句执行的返回值!
  • parameterType:参数类型
    1.编写接口

     /根据id查询用户
    User getUserById(int id);

    2.编写对应的mapper中的sql语句

    <select id="getUserById" parameterType="int" resultType="com.jialidun.pojo.User">
    select * from mybatis.user where id = #{id}
    </select>

    3.测试

     @Test
    public void getUserById(){
       
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       
       UserMapper mapper = sqlSession.getMapper(UserDao.class);
       
      User user = mapper.getUserById(1);
       System.out,println(user);
       sqlSession.close();
    
    
    }

    2.3、Insert

    1.编写接口

    //insert 一个用户
    int addUser(User user);

    2.编写对应的mapper值得sql

    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser" parameterType="com.jialidun.pojo.User">
     insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
    </insert>

    3.测试

     @Test
    public void addUser(){
     SqlSession sqlSession = MybatisUtils.getSqlSession();
       
       UserMapper mapper = sqlSession.getMapper(UserDao.class);
       
      int num = mapper.addUser(4,"沙和尚","444555");
       if(num>0){
         System.out.println("添加用户成功!");
       
       }
       
       //提交事务
       sqlSession.commit();
       sqlSession.close();
    
    }

    2.4、update

    1.编写接口

     //修改用户
    int updateUser(User user);

    2.编写对应的mapper值得sql

    <update id="updateUser" parameterType="com.jialidun.pojo.User">
       update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
    </update>

    3.测试

    @Test
    public void updateUser(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       
       UserMapper mapper = sqlSession.getMapper(UserDao.class);
       
      mapper.updateUser(new User(4,"悟净","666666"));
       //提交事务
       sqlSession.commit();
       sqlSession.close();
    
    }
    

    2.5、delete

    1.编写接口

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

    2.编写对应的mapper值得sql

    <delete id="deleteUser" parameterType="int">
     delete from mybatis.user where id=#{id};
    
    </delete>

    3.测试

    @Test
    public void deleteUser(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       
       UserMapper mapper = sqlSession.getMapper(UserDao.class);
       
      mapper.deleteUser(4);
      
      //提交事务
      sqlSession.commit();
      
       sqlSession.close();
    
    
    }

注意点:

  • 增删改需要提交事务!

3、分析错误

  • 标签不要匹配错
  • resource绑定mapper,需要使用路径!
  • 程序配置文件必须符合规范!
  • NullPointException,没有注册到资源!
  • maveb资源没有导出问题!

RYGAR
1 声望0 粉丝

« 上一篇
Mybatis
下一篇 »
Mybatis中的map

引用和评论

0 条评论