在 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 中處理各種復雜查詢。在實際開發中,可以根據具體需求選擇合適的方法。