在 MyBatis 中处理复杂查询,可以通过以下几种方式实现:
<if>
、<choose>
、<when>
、<otherwise>
等标签,可以在 XML 映射文件中编写动态 SQL,以应对复杂的查询条件。例如:<select id="findUsers" parameterType="map" resultType="User">
SELECT * FROM users
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<resultMap id="userResultMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" javaType="Address">
<id property="id" column="address_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
</association>
</resultMap>
<select id="findUserWithAddress" parameterType="int" resultMap="userResultMap">
SELECT u.*, a.* FROM users u
LEFT JOIN addresses a ON u.address_id = a.id
WHERE u.id = #{id}
</select>
<select id="findUserCountByCity" parameterType="String" resultType="int">
SELECT city, COUNT(*) as userCount
FROM users
GROUP BY city
</select>
<select id="findUserWithNestedQuery" parameterType="int" resultType="User">
SELECT * FROM users
WHERE id IN (
SELECT id FROM users
WHERE age > #{minAge}
)
</select>
首先,在数据库中创建存储过程:
DELIMITER //
CREATE PROCEDURE GetUsersByAgeRange(IN minAge INT, IN maxAge INT, OUT userCount INT)
BEGIN
SELECT COUNT(*) INTO userCount FROM users WHERE age BETWEEN minAge AND maxAge;
END //
DELIMITER ;
然后,在 MyBatis 的映射文件中调用存储过程:
<select id="findUserCountByAgeRange" parameterType="map" statementType="CALLABLE">
{call GetUsersByAgeRange(#{minAge, mode=IN, jdbcType=INTEGER}, #{maxAge, mode=IN, jdbcType=INTEGER}, #{userCount, mode=OUT, jdbcType=INTEGER})}
</select>
通过以上方法,可以在 MyBatis 中处理各种复杂查询。在实际开发中,可以根据具体需求选择合适的方法。