要向數據庫添加數據,可以通過MyBatis使用插入語句來實現。以下是一個簡單的示例:
public interface UserMapper {
void insertUser(User user);
}
<insert id="insertUser" parameterType="com.example.User">
INSERT INTO user (id, username, password) VALUES (#{id}, #{username}, #{password})
</insert>
User user = new User();
user.setId(1);
user.setUsername("john");
user.setPassword("123456");
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertUser(user);
sqlSession.commit();
sqlSession.close();
通過以上步驟,就可以向數據庫中添加數據并提交事務。