MyBatis Insert: Add Database Data
To add data to the database, you need to use MyBatis insert statements. Here are the general steps for adding data to the database using MyBatis:
- Mapping of users
public interface UserMapper {
@Insert("INSERT INTO users (id, name, email) VALUES (#{id}, #{name}, #{email})")
void insertUser(User user);
}
- “Please include all the necessary information in your report.”
- The xml file for mapping users
<?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="com.example.UserMapper">
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO users (id, name, email)
VALUES (#{id}, #{name}, #{email})
</insert>
</mapper>
- – Database session
- – place()
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(1);
user.setName("John");
user.setEmail("john@example.com");
userMapper.insertUser(user);
sqlSession.commit();
} finally {
sqlSession.close();
}
In this way, MyBatis will insert the attribute values of the User object into the database table.