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语句。