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语句。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 怎么有效防止sql注入