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;

pom.xml文件导入相关依赖

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>

    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.0.33</version>
    </dependency>
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

</dependencies>

创建实体类Person

public class Person {
    private int id;
    private String name;
    private String sex;
    private Integer age;
    private String idCard;
    // 忽略了 构造方法和get、set方法
}

创建一个接口PersonMapper

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

package com.test.mapper;

/**
 * 接口代理
 */
public interface PersonMapper {

    /**
     * ====== 查找
     */
    List<Person> selectAll();

}

创建PersonMapper.xml

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

注意

在资源文件下创建多级文件夹,不能使用`.`了,需要使用`/`才能创建成功
<?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:这里需要跟PersonMapper 这个接口进行绑定
-->
<mapper namespace="com.test.mapper.PersonMapper">

    <!--
        数据库表中的字段 和 实体类的属性名称 不一样,就不会自动封装数据,
        所以需要使用resultMap来对不一样的进行映射
    -->
    <resultMap id="personResultMap" type="Person">
        <!--  id 是用来对主键的映射  -->
        <!-- <id property="id" column="id"/> -->
        <result column="id_card" property="idCard"/>
    </resultMap>
</mapper>

创建mybatis-config.xml配置文件

在 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>

    <!--
        设置别名
        在这里设置里以后,在mapper.xml文件中,
        就可以直接使用名字,不用再写包名了
     -->
    <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. 查询所有

// 测试查询所有
@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();

}

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);
}

2. 根据单个条件查询

  1. PersonMapper.java 中添加如下代码
    Person selectById(int id);
    
  2. PersonMapper.xml 中添加如下代码
    <mapper namespace="com.test.mapper.PersonMapper">
        ...
        <select id="selectById" resultMap="personResultMap">
            select *
            from person
            where id = #{id}
        </select>
    </mapper>
    
  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();
    }
    

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

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

  1. PersonMapper.java 中添加如下代码
    //     方式1 多个参数,使用@Param注解
    //    List<Person> selectByCondition(@Param("name") String name, @Param("age") int age, @Param("idCard") String idCard);
    
    //    方式2:通过map传参
    //    List<Person> selectByCondition(Map<String, Object> map);
    
        // 方式3:通过对象传参
        List<Person> selectByCondition(Person person);
    
  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>
    
  3. 单元测试代码
    @Test
    public void testSelectByCondition() throws IOException {
        SqlSession sqlSession = getSqlSession();
        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
        // 方式1
    //        List<Person> list = personMapper.selectByCondition("陆小凤", 23, "100001");
    //        System.out.println(list);
    
        // 方式2
    //        Map<String, Object> map = new HashMap<>();
    //        map.put("name", "陆小凤");
    //        map.put("age", 23);
    //        map.put("idCard", "100001");
    //        List<Person> 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();
    }
    

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

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

  1. PersonMapper.java 中添加如下代码
    // 这里传参方式跟selectByCondition一样也有三种
    List<Person> selectByConditionSingle(Person person);
    
  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>
    
  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. PersonMapper.java 中添加如下代码
    void add(Person p);
    
  2. PersonMapper.xml 中添加如下代码
    <mapper namespace="com.test.mapper.PersonMapper">
        ...
        <!--
            keyProperty 和 useGeneratedKeys 往往搭配使用,
            自动生成主键,并可将自动生成的主键返回
         -->
        <insert id="add" useGeneratedKeys="true" keyProperty="id">
            insert into person(name, age, sex, id_card)
            values (#{name}, #{age}, #{sex}, #{idCard})
        </insert>
    </mapper>
    
  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();
    }
    

修改数据

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

  1. PersonMapper.java 中添加如下代码
    int updateById(Person p);
    
  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>
    
  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. PersonMapper.java 中添加如下代码
    void deleteById(int id);
    
  2. PersonMapper.xml 中添加如下代码
    <mapper namespace="com.test.mapper.PersonMapper">
        ...
        <delete id="deleteById">
            delete
            from person
            where id = #{id}
        </delete>
    </mapper>
    
  3. 单元测试代码
    @Test
    public void testDeleteById() throws IOException {
        SqlSession sqlSession = getSqlSession();
        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);
    
        personMapper.deleteById(10);
    
        sqlSession.close();
    }
    

删除多条数据

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

  1. PersonMapper.java 中添加如下代码
    //    void deleteByIds(int[] ids);
    void deleteByIds(@Param("ids") int[] ids);;
    
  2. PersonMapper.xml 中添加如下代码
    <mapper namespace="com.test.mapper.PersonMapper">
        ...
        <!--
        动态 删除多个
        mybatis 会将数组参数,封装成一个map集合,key是array
        1. 使用默认的 array,
        2. 使用@Param注解修改map集合key 的值
    
        -->
        <delete id="deleteByIds">
            delete
            from person
            where id in
            <!-- <foreach collection="array" item="id" separator="," open="(" close=")">-->
            <foreach collection="ids" item="id" open="(" close=")" separator=",">
                #{id}
            </foreach>
        </delete>
    </mapper>
    
  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. 黑马程序员JavaWeb基础教程
2. MyBatis官网

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ljp345775

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值