xml
<insert id="insertUser" parameterType="User">
INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
对应Java代码:
java
sqlSession.insert("insertUser", user);
sqlSession.commit();
xml
<delete id="deleteUserById" parameterType="int">
DELETE FROM user WHERE id = #{id}
</delete>
对应Java代码:
java
sqlSession.delete("deleteUserById", userId);
sqlSession.commit();
xml
<update id="updateUser" parameterType="User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
对应Java代码:
java
sqlSession.update("updateUser", user);
sqlSession.commit();
xml
<select id="getUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
对应Java代码:
java
User user = sqlSession.selectOne("getUserById", userId);
在MyBatis中,可以使用动态SQL来构建灵活的增删改查语句,以应对不同的查询条件和业务需求。以下是一些常见的动态SQL语法示例:
xml
<select id="getUserByCondition" parameterType="Map" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
对应Java代码:
java
Map<String, Object> params = new HashMap<>();
params.put("name", "John");
List<User> users = sqlSession.selectList("getUserByCondition", params);
xml
<insert id="insertUser" parameterType="User">
INSERT INTO user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">name,</if>
<if test="age != null">age,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">#{name},
<if test="age != null">#{age},
</trim>
</insert>
对应Java代码:
java
User user = new User("Alice", 25);
sqlSession.insert("insertUser", user);
sqlSession.commit();
xml
<update id="updateUser" parameterType="User">
UPDATE user
<set>
<if test="name != null">name = #{name},
<if test="age != null">age = #{age},
</set>
WHERE id = #{id}
</update>
对应Java代码:
java
User user = new User(1, "Bob", 30);
sqlSession.update("updateUser", user);
sqlSession.commit();
xml
<delete id="deleteUserByCondition" parameterType="Map">
DELETE FROM user
<where>
<if test="name != null">AND name = #{name}
<if test="age != null">AND age = #{age}
</where>
</delete>
对应Java代码:
java
Map<String, Object> params = new HashMap<>();
params.put("name", "Tom");
sqlSession.delete("deleteUserByCondition", params);
sqlSession.commit();