您的位置:首页 > 数据库

对持久层sql语句的高复用性的一点小领悟

2017-11-01 17:19 155 查看
一个小例子,我的前台页面注册窗口需要查询用户数据库中的账号是否存在,以及登陆窗口需要验证账号密码是否正确,那么就可以只写一句sql语句,及一个持久层接口方法就可以实现.

传入的参数是一个的bean对象,就可以依靠判断参数是否存在进行不同的查询.代码如下;

1	<select id="selectUserByCondition" resultMap="BaseResultMap">
select * from t_user
where
account = #{account} and password = #{password}
</select>
2	<select id="selectUserByAccount" resultMap="BaseResultMap">
select * from t_user
where
account = #{account}
</select>

3	<select id="selectUserByCondition" resultMap="BaseResultMap">
select * from t_user
<where>
<if test="account!=null">
and account = #{account}
</if>
<if test="password!=null">
and password = #{password}
</if>
<if test="phone!=null">
and phone = #{phone}
</if>
<if test="email!=null">
and email = #{email}
</if>
<if test="age!=null">
and age = #{age}
</if>
</where>
</select>

前两种写法的话,如果查询一个或多个参数,就要有不同的sql语句,写成第三种方式,可以将bean中全部成员变量写上进行判断,就能判断参数是否存在进行查询.可以举一反三,更加有效的简化代码.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: