MyBatis | 변경 UPDATE

변경전 DB 테이블

test_table

id value
1 hoge
2 fuga
3 piyo

소스코드

TestTable.java

package sample.mybatis;

public class TestTable {
    private int id;
    private String value;

    public TestTable(int id, String value) {
        this.id = id;
        this.value = value;
    }
}

sample_mapper.xml

<?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="sample.mybatis">

  <update id="updateTest">
    update test_table
       set value = #{value}
     where id = #{id}
  </update>
</mapper>

Main.java

package sample.mybatis;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

            try (SqlSession session = factory.openSession()) {
                TestTable table = new TestTable(1, "update");

                session.insert("sample.mybatis.updateTest", table);
                session.commit();
            }
        }
    }
}

실행 결과

[DEBUG] s.m.updateTest  - ==>  Preparing: update test_table set value = ? where id = ? 
[DEBUG] s.m.updateTest  - ==> Parameters: update(String), 1(Integer)
[DEBUG] s.m.updateTest  - <==    Updates: 1

test_table

id value
1 update
2 fuga
3 piyo

설명

  • <update> 태그로 UPDATE을 정의할 수 있다.
최종 수정 : 2021-08-26