MyBatis如果想用动态SQL实现ORDER BY和LIMIT语句的运行与否,怎么办?
public List<User> find(String key, Integer offset, Integer rowCount) {
Map<String, Object> params = getParameterMap();
params.put("name", key);
params.put("offset", offset);
params.put("rowCount", rowCount);
return getSqlSession().selectList(User.class.getName().find, params);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.stephen.ssm.model.User">
<resultMap type="User" id="userMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<sql id="pagination">
<if test="offset != null and rowCount!= null">
<![CDATA[
LIMIT #{offset},#{rowCount}
]]>
</if>
</sql>
<select id="find" resultMap="userMap" parameterType="map">
<![CDATA[
SELECT * FROM users WHERE 1 = 1
]]>
<if test="name != null">
<![CDATA[
AND name LIKE CONCAT('%', #{name}, '%')
]]>
</if>
<![CDATA[
ORDER BY id ASC
]]>
<include refid="pagination" />
</select>
<select id="getCount" resultType="Integer" parameterType="map">
<![CDATA[
SELECT COUNT(id) FROM users WHERE 1 = 1
]]>
<if test="name != null">
<![CDATA[
AND name LIKE CONCAT('%', #{name}, '%')
]]>
</if>
</select>
</mapper>
3 回答2.7k 阅读✓ 已解决
3 回答4.2k 阅读✓ 已解决
8 回答3.8k 阅读
4 回答2.8k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
3 回答2.6k 阅读✓ 已解决
4 回答2.1k 阅读
不是很确定您的需求,不过您可以试试在mapper接口上加上 @SelectProvider 这个注解,通过自定义sql的方式,可以根据参数对sql进行不同的处理.相同的,还有 @UpdateProvider , @DeleteProvider , @InsertProvider 这些注解.