• mybatis的简单使用


    数据准备

    create database db_mybatis;
    use db_mybatis;
    
    drop table if exists person;
    
    create table if not exists person
    (
        id      int primary key auto_increment,
        name    varchar(10) not null comment '姓名',
        age     tinyint     not null comment '年龄',
        sex     char(1) default '男' comment '性别',
        id_card char(18)    not null unique comment '身份证'
    );
    
    insert into person(name, sex, age, id_card)
    values ('陆小凤', '男', 23, '100001'),
           ('上官飞燕', '女', 18, '100002'),
           ('西门吹雪', '男', 25, '100003'),
           ('沙曼', '女', 21, '100004'),
           ('花满楼', '男', 21, '100005');
    
    select *
    from person;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    pom.xml文件导入相关依赖

    <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.6version>
        dependency>
    
        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <version>8.0.33version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.2version>
            <scope>testscope>
        dependency>
    
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    创建实体类Person

    public class Person {
        private int id;
        private String name;
        private String sex;
        private Integer age;
        private String idCard;
        // 忽略了 构造方法和get、set方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    创建一个接口PersonMapper

    以后在这个接口里面,添加增删改查的方法

    package com.test.mapper;
    
    /**
     * 接口代理
     */
    public interface PersonMapper {
    
        /**
         * ====== 查找
         */
        List<Person> selectAll();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    创建PersonMapper.xml

    这个需要在resources资源文件下,并且需要跟上面的那个PersonMapper接口保持一样的包名,所以需要先在资源文件下创建同级目录

    注意

    在资源文件下创建多级文件夹,不能使用`.`了,需要使用`/`才能创建成功
    
    • 1
    
    DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.test.mapper.PersonMapper">
    
        
        <resultMap id="personResultMap" type="Person">
            
            
            <result column="id_card" property="idCard"/>
        resultMap>
    mapper>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    创建mybatis-config.xml配置文件

    在 resources 文件夹下创建 mybatis-config.xml

    
    DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        
        <typeAliases>
            <typeAlias type="com.test.pojo.Person" alias="Person"/>
        typeAliases>
    
        <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:///db_mybatis?useServerPrepStmts=true"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root1234"/>
                dataSource>
            environment>
        environments>
        <mappers>
            
            <package name="com.test.mapper"/>
        mappers>
    configuration>
    
    • 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

    查询

    1. 查询所有

    // 测试查询所有
    @Test
    public void testSelectAll() throws IOException {
    
        SqlSession sqlSession = getSqlSession();
    
        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    
        List<Person> list = personMapper.selectAll();
    
        System.out.println(list);
        // 释放资源
        sqlSession.close();
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    getSqlSession()的代码如下

    public SqlSession getSqlSession() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory.openSession(true);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2. 根据单个条件查询

    1. PersonMapper.java 中添加如下代码
      Person selectById(int id);
      
      • 1
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          <select id="selectById" resultMap="personResultMap">
              select *
              from person
              where id = #{id}
          select>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    3. 单元测试代码
      @Test
      public void testSelectById() throws IOException {
      
          SqlSession sqlSession = getSqlSession();
      
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
      
          // 这里的id,后续是从外面传过来的
          int id = 4;
      
          Person p = personMapper.selectById(id);
      
          System.out.println(p.toString());
          // 释放资源
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16

    3. 多个条件的动态sql查询

    主要是练习 mybatis的动态sql里的 whereif 标签

    1. PersonMapper.java 中添加如下代码
      //     方式1 多个参数,使用@Param注解
      //    List selectByCondition(@Param("name") String name, @Param("age") int age, @Param("idCard") String idCard);
      
      //    方式2:通过map传参
      //    List selectByCondition(Map map);
      
          // 方式3:通过对象传参
          List<Person> selectByCondition(Person person);
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          <select id="selectByCondition" resultMap="personResultMap">
              select *
              from person
              <where>
                  <if test="name !=null and name != ''">
                      and name = #{name}
                  if>
                  <if test="age !=null">
                      and age = #{age}
                  if>
                  <if test="idCard !=null and idCard != ''">
                      and id_card = #{idCard}
                  if>
              where>
          select>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
    3. 单元测试代码
      @Test
      public void testSelectByCondition() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
          // 方式1
      //        List list = personMapper.selectByCondition("陆小凤", 23, "100001");
      //        System.out.println(list);
      
          // 方式2
      //        Map map = new HashMap<>();
      //        map.put("name", "陆小凤");
      //        map.put("age", 23);
      //        map.put("idCard", "100001");
      //        List list = personMapper.selectByCondition(map);
      //        System.out.println(list);
      
          // 方式3
          Person person = new Person();
      //        person.setName("陆小凤");
          person.setAge(23);
      //        person.setIdCard("100001");
          List<Person> list = personMapper.selectByCondition(person);
          System.out.println(list);
      
          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

    4. 单个条件的动态sql查询

    主要是练习 mybatis的动态sql里的 whenchoose 标签

    1. PersonMapper.java 中添加如下代码
      // 这里传参方式跟selectByCondition一样也有三种
      List<Person> selectByConditionSingle(Person person);
      
      • 1
      • 2
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          <select id="selectByConditionSingle" resultMap="personResultMap">
              select *
              from person
              <where>
                  <choose>
                      <when test="name != null and name != ''">
                          name = #{name}
                      when>
                      <when test="age != null">
                          age = #{age}
                      when>
                      <when test="idCard !=null and idCard != ''">
                          id_card = #{idCard}
                      when>
                  choose>
              where>
          select>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
    3. 单元测试代码
      @Test
      public void testSelectByConditionSingle() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
      
          Person person = new Person();
          person.setIdCard("100004");
      //        person.setAge(23);
      //        person.setName("花满楼");
      
          List<Person> list = personMapper.selectByConditionSingle(person);
      
          System.out.println(list);
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

    添加数据

    1. PersonMapper.java 中添加如下代码
      void add(Person p);
      
      • 1
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          
          <insert id="add" useGeneratedKeys="true" keyProperty="id">
              insert into person(name, age, sex, id_card)
              values (#{name}, #{age}, #{sex}, #{idCard})
          insert>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
    3. 单元测试代码
      @Test
      public void testAdd() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
          Person person = new Person("王五", "女", 32, "300010");
          personMapper.add(person);
      
          System.out.println("id:" + person.getId());
      
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

    修改数据

    主要是练习 mybatis的动态sql里的 set 标签

    1. PersonMapper.java 中添加如下代码
      int updateById(Person p);
      
      • 1
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          <update id="updateById">
              update person
              <set>
                  <if test="name != null and name != ''">
                      name = #{name},
                  if>
                  <if test="age != null">
                      age = #{age},
                  if>
                  <if test="idCard != null and idCard != ''">
                      id_card = #{idCard},
                  if>
              set>
              where id = #{id}
          update>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
    3. 单元测试代码
      @Test
      public void testUpdateById() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
      
          Person person = new Person();
          person.setId(12);
          person.setAge(88);
          person.setIdCard("aaaaaa");
          personMapper.updateById(person);
      
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

    删除数据

    删除单条数据

    1. PersonMapper.java 中添加如下代码
      void deleteById(int id);
      
      • 1
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          <delete id="deleteById">
              delete
              from person
              where id = #{id}
          delete>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
    3. 单元测试代码
      @Test
      public void testDeleteById() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
      
          personMapper.deleteById(10);
      
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9

    删除多条数据

    主要是为了练习mybatis 的动态sql里的foreach标签

    1. PersonMapper.java 中添加如下代码
      //    void deleteByIds(int[] ids);
      void deleteByIds(@Param("ids") int[] ids);;
      
      • 1
      • 2
    2. PersonMapper.xml 中添加如下代码
      <mapper namespace="com.test.mapper.PersonMapper">
          ...
          
          <delete id="deleteByIds">
              delete
              from person
              where id in
              
              <foreach collection="ids" item="id" open="(" close=")" separator=",">
                  #{id}
              foreach>
          delete>
      mapper>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
    3. 单元测试代码
      @Test
      public void testDeleteByIds() throws IOException {
          SqlSession sqlSession = getSqlSession();
          PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
      
          personMapper.deleteByIds(new int[]{6, 7});
      
          sqlSession.close();
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9

    参考文献

    1. 黑马程序员JavaWeb基础教程
    2. MyBatis官网

  • 相关阅读:
    /usr/bin/env: ‘python’: No such file or directory
    linux权限
    windows中Ubuntu子系统的连接
    十三、vite项目中无法使用minio的解决方案
    2023全新付费进群系统源码 带定位完整版 附教程
    浅谈对接海康SDK语音对讲功能
    【虚幻引擎UE】UE5 C++环境异常原因及解决方案
    C语言解决八皇后问题
    Docker 使用 IDEA 内置插件构建上传镜像 与 SSH、FTP 功能使用
    LeetCode_dijkstra 算法_困难_882.细分图中的可到达节点
  • 原文地址:https://blog.csdn.net/ljp345775/article/details/133918152