案例一:基本查询
技巧解析
MyBatis的基本查询非常简单,只需在Mapper接口中定义方法,然后在对应的XML文件中编写SQL语句即可。
// Mapper接口
public interface UserMapper {
User selectById(int id);
}
// XML文件
<select id="selectById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
实战步骤
- 创建Mapper接口和XML文件。
- 编写SQL查询语句。
- 在Service层调用Mapper接口的方法。
案例二:条件查询
技巧解析
使用MyBatis进行条件查询时,可以使用<if>标签进行动态SQL拼接。
<select id="selectByCondition" resultType="User">
SELECT * FROM users
<where>
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<where>标签和<if>标签编写动态SQL。 - 在Service层调用Mapper接口的方法。
案例三:分页查询
技巧解析
MyBatis支持分页查询,可以通过<limit>标签实现。
<select id="selectByPage" resultType="User">
SELECT * FROM users
<where>
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
LIMIT #{offset}, #{limit}
</select>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<limit>标签进行分页。 - 在Service层调用Mapper接口的方法,并传入页码和每页数量。
案例四:插入操作
技巧解析
MyBatis的插入操作使用<insert>标签,并使用<selectKey>标签获取自增主键。
<insert id="insertUser" parameterType="User">
INSERT INTO users (name, age) VALUES (#{name}, #{age})
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<insert>标签编写插入SQL。 - 在Service层调用Mapper接口的方法,并传入User对象。
案例五:更新操作
技巧解析
MyBatis的更新操作使用<update>标签,可以结合<if>标签进行动态SQL拼接。
<update id="updateUser" parameterType="User">
UPDATE users
<set>
<if test="name != null">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
</set>
WHERE id = #{id}
</update>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<update>标签编写更新SQL。 - 在Service层调用Mapper接口的方法,并传入User对象。
案例六:删除操作
技巧解析
MyBatis的删除操作使用<delete>标签,可以直接编写SQL语句。
<delete id="deleteUser" parameterType="int">
DELETE FROM users WHERE id = #{id}
</delete>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<delete>标签编写删除SQL。 - 在Service层调用Mapper接口的方法,并传入id。
案例七:多表查询
技巧解析
MyBatis支持多表查询,可以使用<resultMap>标签定义结果映射。
<select id="selectUserAndOrder" resultType="UserOrder">
SELECT u.*, o.* FROM users u
INNER JOIN orders o ON u.id = o.user_id
</select>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<resultMap>标签定义结果映射。 - 在Service层调用Mapper接口的方法。
案例八:一对多查询
技巧解析
MyBatis支持一对多查询,可以在<resultMap>标签中使用<collection>标签进行映射。
<select id="selectUserAndOrders" resultType="UserOrder">
SELECT u.*, o.* FROM users u
LEFT JOIN orders o ON u.id = o.user_id
</select>
实战步骤
- 创建Mapper接口和XML文件。
- 在XML文件中使用
<resultMap>标签定义结果映射。 - 在Service层调用Mapper接口的方法。
案例九:缓存机制
技巧解析
MyBatis支持缓存机制,可以提高查询效率。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
实战步骤
- 在Mapper接口上添加
@CacheNamespace注解。 - 在XML文件中配置缓存。
案例十:事务管理
技巧解析
MyBatis支持事务管理,可以使用@Transactional注解或编程式事务。
@Transactional
public void updateUserAndOrder(User user, Order order) {
// ...
}
实战步骤
- 在Service层方法上添加
@Transactional注解。 - 或使用编程式事务管理。
通过以上10个实战案例,相信你已经对MyBatis有了更深入的了解。在实际开发中,多加练习,逐步提高自己的技能水平。祝你在数据库操作的道路上越走越远!
