谈谈IBatis的动态SQL应该改进的架构设计!
SqlMap?的动态SQL是什么?
SqlMap?的动态SQL就是一条sql语句,根据传入的参数情况动态拼装出sql。这也是IBatis引以自豪的强大功能。
IBatis文档称“。如果你有使用JDBC或其他相似框架的经验,你就明白条件地串联SQL字符串在一起是多么的痛苦,确保不能忘了空格或在列表的最后省略逗号。动态SQL可以彻底处理这种痛苦。”。
IBatis的SqlMap?很强大,但我觉得并不完美。这是我理想中的动态SQL以及其使用办法,欢迎讨论:
像IBatis的动态sql控制一样,要有足够的简洁的控制命令:
1. if
2. choose(when,otherwise)
3. where,set
IBatis还有一个foreach,我觉得没什么用,不需要支持(欢迎举例反驳我)。
if用来控制条件判断,如:
<select id=”findActiveBlogWithTitleLike” parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = ?ACTIVE? <if test=”title != null”> AND title like #{title} </if></select>.... SELECT * FROM BLOG <where> <if test=”state != null”> state = #{state} </if> <if test=”title != null”> AND title like #{title} </if> <if test=”author != null and author.name != null”> AND title like #{author.name} </if> </where></select><update id="updateAuthorIfNecessary" parameterType="domain.blog.Author"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id}</update> <if test=”state != null”> state = #{state} </if> <if test=”state > 0 ”> state = #{state} </if> <if test=”createdTime < 2009-10-23 ”> readonly = true </if>
<if test=”state > 0 ”> state = #{state} </if> <if test=”createdTime < 2009-10-23 ”> readonly = true </if> <paramsMapping> <map paramName="state" propName="blogState" /> <map paramName="createdTime" dataType="datetime|yyyy-MM-dd" /> </paramsMapping> <select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = "ACTIVE" <choose> <when test=”title != null”> AND title like #{title} </when> <when test=”author != null and author.name != null”> AND title like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose></select><select id=”findActiveBlogLike” parameterType=”Blog” resultType=”Blog”> SELECT * FROM BLOG WHERE state = "ACTIVE" <choose> <when test=”title.trim().length() > 0”> AND title like #{title} </when> <when test=”author.getName().length() > 0”> AND title like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose></select><if test=”(state > 0 and order ~= 'desc') or (id > 10 and name == 'abc') ”> state = #{state}</if>其他的哪?