MyBatis基础④

举报
十八岁讨厌编程 发表于 2022/08/05 23:48:48 2022/08/05
【摘要】 文章目录 配置文件完成增删改查添加主键返回 修改修改全部字段修改动态字段 删除删除一个批量删除 配置文件完成增删改查 添加 步骤: 详解: ①编写接口方法 ...

配置文件完成增删改查

添加

步骤:
在这里插入图片描述

详解:
①编写接口方法

  /**
   * 添加
   */
void add(Brand brand);

  
 
  • 1
  • 2
  • 3
  • 4

②编写SQL语句

<insert id="add">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>

  
 
  • 1
  • 2
  • 3
  • 4

③编写测试方法

public class Try4 {
    public static void main(String[] args) throws Exception {
        //获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";  //此处填写相对于resources的路径
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //用SqlSessionFactory对象制造SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

//        //用SqlSession对象来执行sql语句
//        List<User> users = sqlSession.selectList("test.selectAll");
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand = new Brand();
        brand.setBrandName("小米");
        brand.setCompanyName("小米公司");
        brand.setOrdered(50);
        brand.setDescription("小米为发烧而生");
        brand.setStatus(1);

        mapper.add(brand);

        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

注意:
使用openSession是默认开启事务的,如果不提交事务的话,数据库不会发生变化。在这里有两种解决办法:
在这里插入图片描述

主键返回

有时候我们需要返回添加数据的主键
比如:添加订单和订单项

  • 添加订单
  • 添加订单项,订单项中需要设置所属订单的id

做法:
在 insert 标签上添加如下属性:

  • useGeneratedKeys:是够获取自动增长的主键值。true表示获取
  • keyProperty :指定将获取到的主键值封装到哪儿个属性里

例如上面的添加的例子中:

<insert id="add" useGeneratedKeys="true" keyProperty="id">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>

  
 
  • 1
  • 2
  • 3
  • 4

再直接用对象的get方法就可以得到当前的主键值了
在这里插入图片描述

修改

修改全部字段

在这里插入图片描述

这个方法也可以返回一个int型,表示受影响的行数

①编写接口方法

Integer setAll(Brand brand);

  
 
  • 1

②编写sql语句

<update id="setAll">
        update mybatis.tb_brand set
            brand_name = #{brandName},
            company_name = #{companyName},
            ordered = #{ordered},
            description = #{description},
            status = #{status}
        where id = #{id};
    </update>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

③执行方法

public static void main(String[] args) throws Exception {
        //获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";  //此处填写相对于resources的路径
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //用SqlSessionFactory对象制造SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

//        //用SqlSession对象来执行sql语句
//        List<User> users = sqlSession.selectList("test.selectAll");
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        Brand brand = new Brand();
        brand.setId(4);
        brand.setBrandName("诺基亚");
        brand.setCompanyName("诺加亚公司");
        brand.setOrdered(50);
        brand.setDescription("让每个人都拥有一台手机");
        brand.setStatus(1);

        mapper.setAll(brand);

        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

修改动态字段

也就是说我们将来要修改哪个字段是不固定的。那么我们的sql语句就不能写死了。这个时候如果我们仍然按照老办法,那么本不需要修改的那些值会被修改为null。

我们的基本思路就是用if标签去包含每一项。

这个地方我们又会遇到前面遇到过问题,就是如果用户什么都没有修改,那么只有一个set在那里肯定会报错。或者用户修改的其中一项而尾部有一个逗号,那么也会报错。这个时候我们就需要用到MyBatis给我们提供的set标签

set 标签可以用于动态包含需要更新的列,忽略其它不更新的列。

我们可以将sql语句改写为:

<update id="setAll">
    update tb_brand
    <set>
        <if test="brandName != null and brandName != ''">
            brand_name = #{brandName},
        </if>
        <if test="companyName != null and companyName != ''">
            company_name = #{companyName},
        </if>
        <if test="ordered != null">
            ordered = #{ordered},
        </if>
        <if test="description != null and description != ''">
            description = #{description},
        </if>
        <if test="status != null">
            status = #{status}
        </if>
    </set>
    where id = #{id};
</update>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

删除

删除一个

思路:
在这里插入图片描述
①编写接口方法

void deleteOne(int id);

  
 
  • 1

②编写sql语句

<delete id="deleteOne">
        delete from mybatis.tb_brand
        where id = #{id};
</delete>


  
 
  • 1
  • 2
  • 3
  • 4
  • 5

③执行方法

public static void main(String[] args) throws Exception {
        //获取SqlSessionFactory对象
        String resource = "mybatis-config.xml";  //此处填写相对于resources的路径
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //用SqlSessionFactory对象制造SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

//        //用SqlSession对象来执行sql语句
//        List<User> users = sqlSession.selectList("test.selectAll");
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        mapper.deleteOne(1);
        sqlSession.commit();


        sqlSession.close();

    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

批量删除

也就是删除多个数据
基本思路:
在这里插入图片描述
步骤详解:
①编写接口方法

/**
  * 批量删除
  */
void deleteByIds(int[] ids);

  
 
  • 1
  • 2
  • 3
  • 4

②编写sql语句
批量删除我们不知道要删除几个,所以编写SQL时需要遍历数组来拼接SQL语句。Mybatis 提供了 foreach 标签供我们使用。

foreach 标签

用来迭代任何可迭代的对象(如数组,集合)。

  • collection 属性:要遍历的可迭代对象
    • mybatis会将数组参数,封装为一个Map集合。
      • 默认:array = 数组
      • 使用@Param注解改变map集合的默认key的名称
  • item 属性:本次迭代获取到的元素。
  • separator 属性:集合项迭代之间的分隔符。foreach 标签不会错误地添加多余的分隔符。也就是最后一次迭代不会加分隔符。
  • open 属性:该属性值是在拼接SQL语句之前拼接的语句,只会拼接一次
  • close 属性:该属性值是在拼接SQL语句拼接后拼接的语句,只会拼接一次
<delete id="deleteByIds">
    delete from tb_brand where id
    in
    <foreach collection="array" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
    ;
</delete>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

假如数组中的id数据是{1,2,3},那么拼接后的sql语句就是:

delete from tb_brand where id in (1,2,3);

   
  
  • 1

③编写测试方法

@Test
public void testDeleteByIds() throws IOException {
    //接收参数
    int[] ids = {5,7,8};

    //1. 获取SqlSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2. 获取SqlSession对象
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //3. 获取Mapper接口的代理对象
    BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
    //4. 执行方法
    brandMapper.deleteByIds(ids);
    //提交事务
    sqlSession.commit();
    //5. 释放资源
    sqlSession.close();
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

文章来源: blog.csdn.net,作者:十八岁讨厌编程,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/zyb18507175502/article/details/124483343

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

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

全部回复

上滑加载中

设置昵称

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

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

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