在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。