使用insert標(biāo)簽進(jìn)行插入操作,如下所示:
<insert id="insertUser" parameterType="User">
INSERT INTO user(username, password) VALUES(#{username}, #{password})
</insert>
然后在Java代碼中調(diào)用:
User user = new User();
user.setUsername("test");
user.setPassword("123456");
sqlSession.insert("insertUser", user);
sqlSession.commit();
使用delete標(biāo)簽進(jìn)行刪除操作,如下所示:
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
然后在Java代碼中調(diào)用:
sqlSession.delete("deleteUser", 1);
sqlSession.commit();
使用update標(biāo)簽進(jìn)行更新操作,如下所示:
<update id="updateUser" parameterType="User">
UPDATE user SET password = #{password} WHERE id = #{id}
</update>
然后在Java代碼中調(diào)用:
User user = new User();
user.setId(1);
user.setPassword("654321");
sqlSession.update("updateUser", user);
sqlSession.commit();
使用select標(biāo)簽進(jìn)行查詢操作,如下所示:
<select id="getUserById" resultType="User" parameterType="int">
SELECT * FROM user WHERE id = #{id}
</select>
然后在Java代碼中調(diào)用:
User user = sqlSession.selectOne("getUserById", 1);
以上就是使用MyBatis進(jìn)行增刪改查操作的基本技巧,通過編寫對(duì)應(yīng)的SQL語句和映射關(guān)系,可以方便地對(duì)數(shù)據(jù)庫進(jìn)行操作。