How is the usage of the insert statement in MyBatis?
In MyBatis, use the insert statement to insert data into the database. The usage of the insert statement is as follows:
- Write the insert statement in the Mapper XML file as shown below:
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
- The insert statement is called in Java code as shown below:
User user = new User();
user.setId(1);
user.setName("Alice");
user.setAge(25);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertUser(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
In the above example, the first step is to create a User object and set its properties. Then, we use SqlSession to retrieve an instance of UserMapper and call the insertUser method to insert data. Lastly, remember to close the SqlSession in the finally block.