MyBatis完成增加和修改操作

文章详细介绍了如何使用MyBatis进行数据操作,包括编写Mapper接口和SQL映射文件来添加数据,测试执行,以及如何处理自动生成的ID。同时,讨论了事务管理和修改动态字段的方法,如利用if标签避免语法错误。
摘要由CSDN通过智能技术生成

添加、修改

1.编写接口方法:Mapper接口
2.编写SQL语句:SQL映射文件
3.试行方法,测试
4.获取id
5.修改动态字段

1.编写Mapper接口方法

void add(Brand brand);

2.编写SQL映射文件

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

注意添加的时候,命名规则的问题。

3.测试

public void testAdd() throws IOException {
        //接收参数
        int status = 1;
        String companyName = "波导手机";
        String brandName = "波导";
        String description = "手机中的战斗机";
        int ordered = 100;

        //封装对象
        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyName(companyName);
        brand.setBrandName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);

        //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.add(brand);

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

        //5. 释放资源
        sqlSession.close();
}

注意:这里有MyBatis事务问题
1.openSession():默认开启事务,进行增删改查操作后需要使用sqlSession.commit();手动提交事务。
2.openSession(true):可以设置为自动提交事务(关闭事务)。mysql中的@@autocommit默认提交方式。

4.获取id

在添加完数据之后,是不能够直接获取id值得。

需要编写SQL语句中添加:

<insert id="add" useGeneratedKeys="true" keyProperty="id">

在插入的时候,id值就已经存在了,只是需要绑定到对应的对象上面,令keyProperty指向id属性的名称即可。

5.修改动态字段

当只用更改部分字段时,SQL语句应该是这样

	<update id="update">
        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>

注意使用set标签:
当其中只有一个SQL字段生效时,后面的逗号就会出现语法错误,为了避免,采用set标签。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值