mybatis-增删改

1、添加,最基本的添加就不在赘述了。

这里需要注意一个知识点:

@Test
    public void Add(){
        int status = 1;
        String companyName = "苹果公司";
        String brandName = "苹果";
        String  ordered = "10";
        String description = "苹果真的6啊";

        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setDescription(description);
        brand.setOrdered(ordered);

        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        SqlSession sqlSession1 = sqlSessionFactory.openSession(true);//自动提交事务
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        brandMapper.add(brand);

//        手动提交事务
        sqlSession.commit();

        sqlSession.close();
    }

这里的事务需要进行提交才会将数据添加进数据库中。

<!--    返回数据添加的主键 useGeneratedKeys="true" keyProperty="id"-->
    <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>

还需要注意的是,在写sql时,需要返回数据添加的主键 useGeneratedKeys="true" keyProperty="id"。

2、动态修改

使用if标签对修改的值进行判断。

<update id="upadte">
        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 and ordered != ''">
            ordered = #{ordered},
        </if>
        <if test="description != null and description != ''">
            description = #{description},
        </if>
        <if test="status != null">
            status = #{status}
        </if>
        where
            id = #{id};
        </set>
    </update>

批量删除

<!--    mybatis 会将数组参数,封装为一个Map集合,
            *默认:array = 数组
            *使用@params注解改变map集合的默认key名称
    -->
    <delete id="deleteByIds">
        delete from tb_brand where id
        in
            <foreach collection="ids" item="id" separator="," open="(" close=")"><!--collections是集合的名称 item为参数 separator是分隔符-->
                #{id}
            </foreach>
            ;
    </delete>

写完这一个CRUD操作,我感觉mybatis确实香,省略了许多js代码,对于日后的开发工作是必不可少的。

注解开发(只适用于sql少,且简单的情况):

@Select("select * from tb_user where id = #{id}")//注解开发
public User selectAllByIdUser(int id);
posted on 2022-07-01 16:45  跨越&尘世  阅读(23)  评论(0编辑  收藏  举报