【JAVAEE框架】Mybatis常用操作(CRUD)

举报
追zhui 发表于 2025/11/13 20:35:24 2025/11/13
【摘要】  ![img](https://img-blog.csdnimg.cn/ebf56577e58a4d55a674c4616280b205.gif#pic_center)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑>  哈喽~大家好呀,这篇来看看...

 

![img](https://img-blog.csdnimg.cn/ebf56577e58a4d55a674c4616280b205.gif#pic_center)

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

>  哈喽~大家好呀,这篇来看看使用的常用操作。
>
>  
>
>  
>
>  🥇个人主页:[个人主页](https://blog.csdn.net/aasd23?spm=1000.2115.3001.5343)        
>
>  🥈 系列专栏:[【JAVAEE框架】](https://blog.csdn.net/aasd23/category_12005462.html?spm=1001.2014.3001.5482)
>
>  🥉与这篇相关的文章:       
>
>  
>
>  | 【JAVAEE框架】Mybatis项目起步讲解                          | [【JAVAEE框架】Mybatis项目起步讲解_程序猿追的博客-CSDN博客](https://blog.csdn.net/aasd23/article/details/126713844) |
>  | ---------------------------------------------------------- | ------------------------------------------------------------ |
>  | JAVAWEB开发】基于Java+Servlet+Ajax+jsp网上购物系统设计实现 | [【JAVAWEB开发】基于Java+Servlet+Ajax+jsp网上购物系统设计实现_程序猿追的博客-CSDN博客](https://blog.csdn.net/aasd23/article/details/126644476?spm=1001.2014.3001.5501) |
>  | Servlet 架构思路(MVC)                                    | [Servlet 架构思路(MVC)_程序猿追的博客-CSDN博客](https://blog.csdn.net/aasd23/article/details/126375547?spm=1001.2014.3001.5501) |

**目录**

[一、准备工作](#一、准备工作)

[二、查询所有用户信息](#二、查询所有用户信息)

[三、按 xx 进行查询](# 三、按 xx 进行查询)

[四、模糊查询](#四、模糊查询)

[五、增删改操作](#五、增删改操作)

[六、联合查询](# 六、联合查询)

[七、分页查询](#七、分页查询)

------


# 一、准备工作

如何新建 Mybatis 项目,可以看看上一篇的讲解——[【JAVAEE框架】Mybatis项目起步讲解](https://blog.csdn.net/aasd23/article/details/126713844?spm=1001.2014.3001.5501)

> 准备 tb_brand 表,字段id(id)、品牌名(brand_name)、公司名(company_name)、排序顺序(ordered)、描述信息(description)、状态(status)。
>
> ![img](https://img-blog.csdnimg.cn/e93842efc3f646f99c2677ee52b41e48.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

项目结构在上篇有所讲解,这里就不重复了,直接上代码讲解。

# 二、查询所有用户信息

我们常见的 xx 管理系统最常见的操作之一,查看所有的记录。

**mapper**

```java
<?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">
<mapper namespace="com.itxzw.dao.IBrandDao">

    <select id="getUserList" resultType="Brand">
        select * from tb_brand
    </select>

</mapper>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**IBrandDao**

```java
public interface IBrandDao {

    public List<Brand> getUserList() throws Exception;

}
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

> 接着上次的讲,上次我们讲到SqlSession是dao与db建立的一次会话,就像 servlet 的 session 一样,但,有没有想过,我们以后一个项目有成千上万的访问者访问页面(获取 db 的信息),那么岂不是要建立成千上万次会话?这是很不合理的。所以就有了 MyBatisUtil,就像 jdbc 的 Util 一样

**MyBatisUtil**

```java
public class MyBatisUtil {

    private static SqlSessionFactory factory;

    static {

        try {
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();

            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");

            factory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSession openSession(){
        return factory.openSession();
    }

    public static SqlSession openSession(boolean autoCommit){
        return factory.openSession(autoCommit);
    }

}
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**实体类(Brand)**

```java
public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brand_name;
    // 企业名称
    private String company_name;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;

    public Brand() {
    }

    public Brand(Integer id, String brand_name, String company_name, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brand_name = brand_name;
        this.company_name = company_name;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBrand_name() {
        return brand_name;
    }

    public void setBrand_name(String brand_name) {
        this.brand_name = brand_name;
    }

    public String getCompany_name() {
        return company_name;
    }

    public void setCompany_name(String company_name) {
        this.company_name = company_name;
    }

    public Integer getOrdered() {
        return ordered;
    }

    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Brand{" +
                "id=" + id +
                ", brand_name='" + brand_name + '\'' +
                ", company_name='" + company_name + '\'' +
                ", ordered=" + ordered +
                ", description='" + description + '\'' +
                ", status=" + status +
                '}';
    }
}
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
public class TestMyBatis {

    @Test
    public void test01() throws Exception {

        IBrandDao userDao = new BrandDao();

        List<Brand> userList = userDao.getUserList();

        for (Brand brand : userList) {
            System.out.println(brand);
        }


    }

}
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/662bf88e05ff4a32b02d0544d2f08856.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

#  三、按 xx 进行查询

常见的按照姓名查询、按照 id 查询等,这里就演示 id 查询

**mapper**

```java
    <select id="getBrandById" resultType="Brand" parameterType="java.lang.String">
        select * from tb_brand where id = #{id}
    </select>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**IBrandDao**

这里就全部给了,这小节就不多写 IBrandDao 了

```java
public interface IBrandDao {

    public List<Brand> getBrandList();

    public Brand getBrandById(String id);

    public List<Brand> getBrandListByCondition(Brand conn);

    public List<Brand> getBrandListByCondition(Map<String,String> conn);

    public Integer addBrand(Brand brand);

    public Integer updateBrand(Brand brand);

    public Integer deleteBrand(Brand brand);

    public Integer getBrandByCondition(Brand brand);

}
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
    @Test
    public void test02(){
        IBrandDao dao = new BrandDao();

        Brand brandList = dao.getBrandById("142");

        System.out.println(brandList);

    }
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/7587a3baaa0e4a05a9de94b907ae5e14.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

# 四、模糊查询

查询品牌含有8的品牌名

**mapper**

```java
    <select id="getBrandListByCondition" resultType="Brand" parameterType="Brand">
        <![CDATA[
            select t.id,
                   t.brand_name,
                   t.company_name,
                   t.description,
                   t.status,
                   t.ordered
            from tb_brand t where
        ]]>

        <if test="id != null and id != '' ">
            <![CDATA[
                id = #{id}
                    ]]>
        </if>

        <if test="brand_name != null and brand_name != '' ">
            <![CDATA[
                 brand_name like '%${brand_name}%'
                     ]]>
        </if>

        <if test="company_name != null and company_name != '' ">
            <![CDATA[
               and company_name like '%${company_name}%'
                    ]]>
        </if>

<!--       <if test="description != null and description '' ">-->
<!--            <![CDATA[-->
<!--                and description like '%${description}%'-->
<!--                    ]]>-->
<!--        </if>-->

<!--        <if test="status != null and status != '' ">-->
<!--            <![CDATA[-->
<!--                and status = #{status}-->
<!--                    ]]>-->
<!--        </if>-->

<!--        <if test="ordered != null and ordered != '' ">-->
<!--            <![CDATA[-->
<!--                and ordered = #{ordered}-->
<!--                    ]]>-->
<!--        </if>-->

    </select>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
    @Test
    public void test03(){
        SqlSession sqlSession = MyBatisUtil.openSession();

        IBrandDao mapper = sqlSession.getMapper(IBrandDao.class);

        Brand brand = new Brand();
        brand.setBrand_name("8");
//        brand.setCompany_name("小米");

        List<Brand> brandList = mapper.getBrandListByCondition(brand);

        for (int i = 0; i < brandList.size(); i++) {
            System.out.println(brandList.get(i));
        }

    }
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/2b1d6ef5b680405096ab9e343f398f1f.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

> **扩:**
>
> <![CDATA[]]> 用法
>
> 在使用mybatis 时我们sql是写在xml 映射文件中,如果写的sql中有一些特殊的字符的话,在解析xml文件的时候会被转义,但我们不希望他被转义,所以我们要使用<![CDATA[ ]]>来解决。
>
> eg:> < 这两个符号

# 五、增删改操作

**mapper**

```java
    <insert id="addBrand" parameterType="Brand">
        <![CDATA[
            insert into tb_brand values (#{id}, #{brand_name}, #{company_name}, #{ordered}, #{description}, #{status});
        ]]>
    </insert>

    <update id="updateBrand" parameterType="Brand">
        <![CDATA[
            update tb_brand set company_name = #{company_name} where id = #{id}
        ]]>
    </update>

    <delete id="deleteBrand" parameterType="Brand">
        <![CDATA[
            delete from tb_brand where id = #{id}
        ]]>
    </delete>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
    @Test
    public void test04(){
        SqlSession sqlSession = MyBatisUtil.openSession();

        IBrandDao mapper = sqlSession.getMapper(IBrandDao.class);

        Brand brand = new Brand(null, "菠萝手机","菠萝",100,"美国有苹果,中国有菠萝",0);

        Integer integer = mapper.addBrand(brand);
        sqlSession.commit();

        System.out.println(integer);

    }


    @Test
    public void test05(){
        SqlSession sqlSession = MyBatisUtil.openSession();

        IBrandDao mapper = sqlSession.getMapper(IBrandDao.class);

        Brand brand = new Brand();
        brand.setId(191);
        brand.setCompany_name("大菠萝手机");

        Integer integer = mapper.updateBrand(brand);
        sqlSession.commit();

        System.out.println(integer);

    }

    @Test
    public void test06(){
        SqlSession sqlSession = MyBatisUtil.openSession();

        IBrandDao mapper = sqlSession.getMapper(IBrandDao.class);

        Brand brand = new Brand();
        brand.setId(195);

        Integer integer = mapper.deleteBrand(brand);
        sqlSession.commit();

        System.out.println(integer);

    }
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/b1dece5ef32a45d78b962f248fec59fb.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

 ![img](https://img-blog.csdnimg.cn/0434ef2e9baa44f08e6743a21c835989.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

![img](https://img-blog.csdnimg.cn/cf3d04995c084f099a3798543b8163e9.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

 ![img](https://img-blog.csdnimg.cn/2e26cd92d78c4ac6ac4375ef4eadc118.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

![img](https://img-blog.csdnimg.cn/776e86f8b0e14f0d9aafb46c3e51e13c.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

#  六、联合查询

**mapper**

```java
  <resultMap id="smbmsUser" type="smbmsUser">
        <id property="id" column="id"></id>
        <association property="role" column="userrole" resultMap="smbmsRole"></association>
        <collection property="addresses" column="id" ofType="smbmsAddress" resultMap="smbmsAddress"></collection>
    </resultMap>

    <resultMap id="smbmsRole" type="smbmsRole">
        <id property="id" column="rid"></id>
        <result property="createdby" column="rcb"></result>
        <result property="creationdate" column="rcd"></result>
        <result property="modifyby" column="rmb"></result>
        <result property="modifydate" column="rmd"></result>
    </resultMap>

    <resultMap id="smbmsAddress" type="smbmsAddress">
        <id property="id" column="aid"></id>
        <result property="createdby" column="acb"></result>
        <result property="creationdate" column="acd"></result>
        <result property="modifyby" column="amb"></result>
        <result property="modifydate" column="amd"></result>
    </resultMap>

    <select id="getUserListByCondition" parameterType="userCondition" resultMap="smbmsUser">

        <![CDATA[
            select
                   u.ID,
                   u.USERCODE,
                   u.USERNAME,
                   u.USERPASSWORD,
                   u.GENDER,
                   u.BIRTHDAY,
                   u.PHONE,
                   u.ADDRESS,
                   u.userrole,
                   r.id rid,
                   r.rolecode,
                   r.rolename,
                   r.createdby rcb,
                   r.creationdate rcd,
                   r.modifyby rmb,
                   r.modifydate rmd,
                   a.id aid,
                   a.contact,
                   a.addressdesc,
                   a.postcode,
                   a.tel,
                   a.createdby acb,
                   a.creationdate acd,
                   a.modifyby amb,
                   a.modifydate amd,
                   a.userid,
                   u.CREATEDBY,
                   u.CREATIONDATE,
                   u.MODIFYBY,
                   u.MODIFYDATE
            from SMBMS_USER u
                     left join smbms_role r
                               on u.userrole = r.id
                     left join smbms_address a
                               on u.id = a.userid
            where 1=1
        ]]>


    </select>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**IUserDao**

```java
    public List<SmbmsUser> getUserListByCondition(UserCondition conn);
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
    @Test
    public void test01(){

        SqlSession sqlSession = MyBatisUtil.openSession();

        IUserDao mapper = sqlSession.getMapper(IUserDao.class);


        UserCondition conn = new UserCondition();

        List<SmbmsUser> userList = mapper.getUserListByCondition(conn);
        for (SmbmsUser smbmsUser : userList) {
            System.out.println(smbmsUser);
        }


        sqlSession.close();
    }
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/c104aec501364a3a9b1351b138f70dd1.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑


# 七、分页查询

**mapper**

```java
    <select id="selectByPage" parameterType="Brand" resultType="Brand">
        select * from tb_brand limit #{begin}, #{size}
    </select>
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

 **IUserDao**

```java
public List<Brand> selectByPage(@Param("begin") int begin, @Param("size") int size);
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**测试**

```java
    @Test
    public void test01() {

        SqlSession sqlSession = MyBatisUtil.openSession();

        IUserDao mapper = sqlSession.getMapper(IUserDao.class);

        List<Brand> pageBean = mapper.selectByPage(1, 10);

        for (Brand brand : pageBean) {
            System.out.println(brand);
        }

        sqlSession.close();
    }
```

![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

**效果**

![img](https://img-blog.csdnimg.cn/152380da67634b65a69c44588bfd2519.png)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑


> **不积跬步无以至千里,趁年轻,使劲拼,给未来的自己一个交代!向着明天更好的自己前进吧!**
>

>
> ![img](https://img-blog.csdnimg.cn/02bed6ae9d27419b804c4605db6cee66.gif)![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)编辑

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。