今天写一个条件查询的时候遇到了问题,也是很久没写了,最后终于解决了
- 首先在dao层接口的参数上加上@Param注解,查询单个参数可以不加,多个必须加上
- @Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中
正确写法
List<GmVipMember> selectByRealNameMemIdTelNum(@Param("realName") String realName,@Param("memId") String memId,@Param("telNum") String telNum)throws Exception;
错误写法
List<GmVipMember> selectByRealNameMemIdTelNum(String realName,String memId,String telNum)throws Exception;
还有动态sql语句的写法
- 1.注意:第一个if标签里面不用and连接,因为是第一个参数所以不用连接
<select id="selectByRealNameMemIdTelNum" resultType="com.gmos.vip.system.model.GmVipMember"
parameterType="java.lang.String">
select
*
from gm_vip_member
where
<if test="realName!=null and realName!=''">
real_name = #{realName,jdbcType=VARCHAR}
</if>
<if test="memId!=null and memId!=''">
and mem_id = #{memId,jdbcType=VARCHAR}
</if>
<if test="telNum!=null and telNum!=''">
and tel_num = #{telNum,jdbcType=VARCHAR}
</if>
</select>
- 2.使用where标签可以解决and的问题
<select id="selectByRealNameMemIdTelNum" resultType="com.gmos.vip.system.model.GmVipMember"
parameterType="java.lang.String">
select
*
from gm_vip_member
<where>
<if test="realName!=null and realName!=''">
and real_name = #{realName,jdbcType=VARCHAR}
</if>
<if test="memId!=null and memId!=''">
and mem_id = #{memId,jdbcType=VARCHAR}
</if>
<if test="telNum!=null and telNum!=''">
and tel_num = #{telNum,jdbcType=VARCHAR}
</if>
</where>
</select>