1、增加(Insert):
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();
2、删除(Delete):
xml
<delete id="deleteUserById" parameterType="int">DELETE FROM user WHERE id = #{id}
</delete>
对应Java代码:java
sqlSession.delete("deleteUserById", userId);
sqlSession.commit();
3、修改(Update):
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();
4、查询(Select):
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语法示例:
5、动态条件查询:
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);
6、动态插入:
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><if test="age != null">#{age},</if></trim>
</insert>
对应Java代码:java
User user = new User("Alice", 25);
sqlSession.insert("insertUser", user);
sqlSession.commit();
7、 动态更新:
xml
<update id="updateUser" parameterType="User">UPDATE user<set><if test="name != null">name = #{name},</if><if test="age != null">age = #{age},</if></set>WHERE id = #{id}
</update>
对应Java代码:java
User user = new User(1, "Bob", 30);
sqlSession.update("updateUser", user);
sqlSession.commit();
8、动态删除:
xml
<delete id="deleteUserByCondition" parameterType="Map">DELETE FROM user<where><if test="name != null">AND name = #{name}</if><if test="age != null">AND age = #{age}</if></where>
</delete>
对应Java代码:java
Map<String, Object> params = new HashMap<>();
params.put("name", "Tom");
sqlSession.delete("deleteUserByCondition", params);
sqlSession.commit();