在MyBatis中,使用insert语句来向数据库中插入数据。insert语句的用法如下:
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
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();
}
以上示例中,首先创建一个User对象并设置属性,然后通过SqlSession获取UserMapper实例,并调用insertUser方法插入数据。最后记得在finally块中关闭SqlSession。