MyBatis動態SQL編寫的方法有以下幾種:
示例:
<select id="getUserList" resultType="User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
示例:
@SelectProvider(type = UserSqlProvider.class, method = "getUserList")
List<User> getUserList(@Param("name") String name, @Param("age") Integer age);
public class UserSqlProvider {
public String getUserList(Map<String, Object> paramMap) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM user WHERE 1=1");
if (paramMap.get("name") != null) {
sql.append(" AND name = #{name}");
}
if (paramMap.get("age") != null) {
sql.append(" AND age = #{age}");
}
return sql.toString();
}
}
示例:
@SelectProvider(type = UserSqlProvider.class, method = "getUserList")
List<User> getUserList(@Param("name") String name, @Param("age") Integer age);
public class UserSqlProvider {
@ProviderMethod
public String getUserList(@Param("name") String name, @Param("age") Integer age) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM user WHERE 1=1");
if (name != null) {
sql.append(" AND name = #{name}");
}
if (age != null) {
sql.append(" AND age = #{age}");
}
return sql.toString();
}
}
以上是幾種常用的MyBatis動態SQL編寫方法,開發人員可以根據自己的需求選擇適合的方法來編寫動態SQL語句。