MyBatis基础④

配置文件完成增删改查

添加

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

详解:
①编写接口方法

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

②编写SQL语句

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

③编写测试方法

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

    }
}

注意:
使用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>

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

修改

修改全部字段

在这里插入图片描述

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

①编写接口方法

Integer setAll(Brand brand);

②编写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>

③执行方法

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

    }

修改动态字段

也就是说我们将来要修改哪个字段是不固定的。那么我们的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>

删除

删除一个

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

void deleteOne(int id);

②编写sql语句

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

③执行方法

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

    }

批量删除

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

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

②编写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>

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

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

③编写测试方法

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

猜你喜欢

转载自blog.csdn.net/zyb18507175502/article/details/124483343