Four, Mybatis writes data

One, Mybatis write operations include three types:

  • insert

  • Update

  • delete

Second, the database transaction:

After the client initiates a connection operation to mysql, if it encounters a write operation, it is not directly written to a table, but needs to be recorded by the transaction log (similar to a running account), and then when the client initiates a commit command to mysql , The transaction log will write the data to the data table at the same time, and the real write will be after the commit. When the data is successfully written into the data table, the transaction log will be cleared. If some data is not executed successfully when the client is processing data, the client will initiate a rollback rollback command. When mysql receives the rollback command, all the data that has been generated in the current transaction log will be cleared, and these data will not be released. In the data table, only when all the data is completed and the client initiates a submission request, our data will be successfully written.
Insert picture description here
Three, Mybatis adds data

The new operation is a bit more complicated than the update and delete operations. After adding the data, because in most cases, the id is automatically generated. After adding the data, we hope that the original data object will get the newly inserted data. Number, we need to add the selectkey subtag in the insert statement, specify select last_insert_id() in the tag, get the last id number generated by the current database connection, and re-assign it to goods_id

Configuration file

<?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="goods">
    <insert id="insert" parameterType="com.imooc.mybatis.entity.Goods">
        insert into t_goods(title,sub_title,original_cost,current_price,discount,is_free_delivery,category_id)
        values (#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId})
        <!--order:执行顺序,设置成after表示在上面语句执行后操作。resultType:设置的函数的返回值类型,keyProperty:要设置的
         上面语句执行完毕后,执行下面的sql语句,将得到的值回添到goodsid属性中-->
        <selectKey resultType="integer" keyProperty="id" order="AFTER">
           <!-- 获取当前连接最后产生的id号,并自动填充给goods里面的id主键属性-->
            select last_insert_id()
        </selectKey>
    </insert>
</mapper>

Code

@Test
public void testSelect() {
    
    
    SqlSession sqlSession = null;
    try {
    
    
        sqlSession = MyBatisUtils.openSession();
        Goods goods = new Goods();
        goods.setTitle("测试商品");
        goods.setSubTitle("测试子商品");
        goods.setCurrentPrice(30.2f);
        goods.setDiscount(2f);
        goods.setIsFreeDelivery(1);
        goods.setOriginalCost(300f);
        goods.setCategoryId(12);
        // insert方法返回插入成功的数量
        int num = sqlSession.insert("goods.insert", goods);
        System.out.println(goods.getTitle());
        // 提交
        sqlSession.commit();
    } catch (Exception e) {
    
    
        // 回滚
        if (sqlSession != null) {
    
    
            sqlSession.rollback();
        }
        throw e;
    } finally {
    
    
        MyBatisUtils.closeSqlSession(sqlSession);
    }
}

Fourth, selectKey and useGeneratedKeys

We mentioned above that when inserting data, if you need to get the auto-incrementing primary key, you need to use selectKey to get it. In addition to using this method, we can also use the useGeneratedKeys method to obtain the primary key, as follows:

 <!--keyProperty:在实体类里的id名称,keyColumn:表里的id名称,useGeneratedKeys:是否自动生成主键,默认是否-->
<insert id="insert" parameterType="com.imooc.mybatis.entity.Goods" useGeneratedKeys="true"
        keyProperty="id" keyColumn="goods_id">
    insert into t_goods(title,sub_title,original_cost,current_price,discount,is_free_delivery,category_id)
    values (#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId})
</insert>

Comparison of the two writing methods:
Insert picture description here
Insert picture description here
The difference between selectKey and useGeneratedKeys:

  1. Display and implicit: The
    selectKey tag needs to explicitly write the SQL statement to obtain the latest primary key: (select last_insert_id()
    useGeneratedKeys attribute will automatically generate the corresponding SQL statement according to the driver, and it will automatically change with the change of the database
  2. Different application scenarios:
    seleKey is applicable to all relational databases.
    useGeneratedKeys only supports auto-incrementing primary key databases (supported databases such as mysql, sqlserver, and unsupported databases are Oracle, etc.).
    Summary: The
    selectKey tag is a general solution, applicable to all databases , But it is troublesome to write (because each database obtains the latest primary key in different ways), it is suitable for complex application scenarios, such as large company projects that have multiple databases to support and save data.
    useGeneratedKeys only supports self-incrementing primary key type databases. Simple to use (applicable to most scenarios, recommended)
    Insert picture description here

Five, update and delete operations

  1. Update:
    Update is to process the existing data. It is not recommended to organize the original data by manual set. It is recommended to obtain the original data first, and then update the original data to ensure that the impact of the data is minimal. The
    configuration is as follows:
<update id="update" parameterType="com.imooc.mybatis.entity.Goods">
    update t_goods set title= #{title} where goods_id= #{id};
</update>
  @Test
    public void testUpdate() {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            Goods goods = sqlSession.selectOne("goods.selectById", 2680);
            goods.setTitle("更新商品");
            int num = sqlSession.update("goods.update", goods);
            sqlSession.commit();
            System.out.println(goods.getTitle());
            System.out.println(goods.getSubTitle());
        } catch (Exception e) {
    
    
            if (sqlSession != null) {
    
    
                sqlSession.rollback();
            }
        } finally {
    
    
            sqlSession.close();
        }
    }
  1. Delete:
    Because most delete operations are performed based on the primary key, when configuring the xml file, the parameterType only needs to declare that the primary key type is int.
    Configuration:
<delete id="delete" parameterType="int">
    delete from t_goods where goods_id=#{id}
</delete>
  @Test
    public void testDelete() {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            int num = sqlSession.delete("goods.delete", 2680);
            sqlSession.commit();
        } catch (Exception e) {
    
    
            if (sqlSession != null) {
    
    
                sqlSession.rollback();
            }
        } finally {
    
    
            sqlSession.close();
        }
    }

Guess you like

Origin blog.csdn.net/qq_36792120/article/details/112343009
Recommended