项目用的是SSM框架,遇到以下的问题,在此做个备忘录, 主要是sql在mybatis的写法:
1.MyBatis的模糊查询
user_name 为数据库中的字段
search_name 为前端传过来的值
在oracle中的写法:
<select id="getUserByName" parameterType="java.lang.String" resultType="com.hueizhe.entity.User">
select * from t_user where user_name like '%'||#{search_name}||'%'
</select>
在MySQL中的写法:
<select id="getUserByName" parameterType="java.lang.String" resultType="com.hueizhe.entity.User">
select * from tb_user where user_name like CONCAT('%',#{search_name},'%')
</select>
2.时间段查询
tb_begin_time 为数据库里的字段
begin_time 为传进来的参数
<if test="begin_date!=null and begin_date!=''">
<![CDATA[
and DATE_FORMAT( tb_begin_time, '%Y-%m-%d') >=DATE_FORMAT(#{begin_date}, '%Y-%m-%d')
]]>
</if>
3.如果是查询出的是 NULL 要显示为0或者其他信息
mysql里的写法:
<!--mysql if null then show 0 or other message-->
IF(countRenew IS NULL, 0,countRenew) as countRenew
IF(phone IS NULL, 'Unknow phone number', phone) as phone
oracle里的写法:
<!--oracle if null then show 0 or other message -->
NVL(countRenew, '0') as countRenew
NVL(phone, 'Unknow phone number') as phone
4.如果变量(例如:password)不是数据库表里的字段,可以在实体层添加,并添加get, set方法,然后再mybatis 的xml文件中的resultMap添加一栏result, 这样就可以在JSP中,就可以用EL表达式 通过 ${对象名.变量名} 的方式调用数据
<resultMap id="dateInfoResultMap" type="com.sinosoft.entity.DateInfo">
<result column="PASSWORD" property="passWord" jdbcType="VARCHAR" />
</result>