MyBatis | INSERT | Passing an Object as a Parameter
Source code
TestTable.java
package sample.mybatis;
public class TestTable {
private int id;
private String value;
public TestTable(String value) {
this.value = value;
}
@Override
public String toString() {
return "TestTable [id=" + id + ", value=" + value + "]";
}
}
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("fuga");
session.insert("sample.mybatis.insertTest", table);
session.commit();
}
}
}
}
Execution result
[DEBUG] s.m.insertTest - ==> Preparing: insert into test_table ( value ) values ( ? )
[DEBUG] s.m.insertTest - ==> Parameters: fuga(String)
[DEBUG] s.m.insertTest - <== Updates: 1
test_table
| id | value |
|---|---|
| 1 | hoge |
| 2 | fuga |
Explanation
- This is also the same as with
<select>. - parameterType can be omitted.