mybatis增删改查


  声明:使用mybatis,本身不需要再写dao的实现类,此处为了保持三层架构的完整性,遂添加了接口dao的实现类

1.增加

  sql语句-->有默认返回类型,一般是int(表示影响行数的意思)

<!-- 新增班级 -->
<insert id="addClass" parameterType="Clazz">
  <!-- 使用序列 -->
  <selectKey keyProperty="cid" order="BEFORE" resultType="int">
    select seq_class1.nextval from dual
  </selectKey>
  insert into class1 values(#{cid},#{cname})
</insert>

  对应的方法

/**
 * 新增班级,此处返回值类型int/void 都可以
 */
public int addClass(Clazz clazz) {
  SqlSession session = super.getSqlSession();
  return session.insert("com.dao.IClassDao.addClass",clazz);
}

2.修改

进行修改,需分两步进行
  步骤一:根据要修改实体的id,将该实体所有信息从数据库中查询出来
    sql语句-->需指定返回值类型

<!-- 根据id获取班级信息 -->
<select id="getClassById" parameterType="int" resultType="Clazz">
  select * from class1 where cId=#{cid}
</select>

  对应的方法

/**
 * 修改前得先获取该班级的所有信息
 */
public Clazz getClassById(int cId) {
  SqlSession session = super.getSqlSession();
  return session.selectOne("com.dao.IClassDao.getClassById",cId);
}

  步骤二:该修改后的实体重新插入数据库中
    sql语句-->需指定参数类型,默认返回类型为int,不用在sql语句声明返回值,否则报错

<!-- 修改班级信息 -->
<update id="updateClass" parameterType="Clazz">
  update class1 set cName=#{cname} where cId=#{cid}    
</update>

  对应的方法

/**
 * 修改班级信息,此处返回值类型int/void 都可以
 */
public int updateClass(Clazz clazz) {
  SqlSession session = super.getSqlSession();
  return session.update("com.dao.IClassDao.updateClass",clazz);
}

2024-10-12 11:41:47

update使用CASE WHEN THEN END

<update id="updateRoleModuleList" parameterType="java.util.List">
	update base_ac_role_module
	<trim prefix="set" suffixOverrides=",">
		<trim prefix="isOper = case" suffix="end,">
			<foreach collection="roleModuleList" item="item" index="index">
				<if test="item.isOper != null">
					when roleId=#{item.roleId} and moduleId=#{item.moduleId} then #{item.isOper}
				</if>
			</foreach>
		</trim>
		<trim prefix="isAuth = case" suffix="end,">
			<foreach collection="roleModuleList" item="item" index="index">
				<if test="item.isAuth != null">
					when roleId=#{item.roleId} and moduleId=#{item.moduleId} then #{item.isAuth}
				</if>
			</foreach>
		</trim>
	</trim>
	where roleId in
	<foreach collection="roleModuleList" separator="," item="item" index="index" open="(" close=")">
		#{item.roleId}
	</foreach>
	and moduleId in
	<foreach collection="roleModuleList" separator="," item="item" index="index" open="(" close=")">
		#{item.moduleId}
	</foreach>
</update>

3.查询

  查询主要是按查询条件进行查询:一般分为根据id查询;根据name进行查询(这里表中的字段name可以重复);组合查询;无查询条件查询
  类型一:根据id进行查询
    例子同修改的步骤一
  类型二:根据name进行查询
    sql语句-->需指定参数类型和返回值类型

<!-- 根据姓名获取学生信息 -->
<select id="getStudentsBysName" parameterType="String" resultType="Student">
  select * from student1 where sName=#{sname}
</select>

  对应的方法

/**
 * 根据姓名获取学生信息
 */
public List<Student> getStudentsBysName(String sName) {
  SqlSession session = super.getSqlSession();
  return session.selectList("com.dao.IStudentDao.getStudentsBysName",sName);
}

  小结:类型一和类型二的区别在于:方法的返回值不同,前者的返回值是唯一的,后者的返回值一般是一个集合
  

注意:select必须带resultType或着resultMap用来接收返回的表数据

否则,将出现上述报错信息。

  类型三:组合查询
    需指定映射关系及类型-->map的键和值的名字保持一致,并和实体类的属性保持一致,否则运行时会报错

<parameterMap type="java.util.Map" id="paramUserMap">
  <parameter property="userName" javaType="String"></parameter>
  <parameter property="userPass" javaType="String"></parameter>
</parameterMap>    

    sql语句-->需指定参数类型和返回值类型

<!-- id的值对应该类中的方法名 -->
<select id="getUsersByNamePass" parameterMap="paramUserMap" resultType="User">
  select * from user1 where 1=1
  <if test="userName != null and userName != ''">
    and userName=#{userName}
  </if>
  <if test="userPass != null and userPass != '' ">
  and userPass=#{userPass}
  </if>
</select>

    对应的方法-->传入的是一个map集合

/**
 * 组合查询:根据用户名和身份查询用户信息
 */
public List<User> getUsersByNamePass(Map user) {
  SqlSession session = super.getSqlSession();
  return session.selectList("com.dao.IUserDao.getUsersByNamePass", user);
}

  类型四:获取表中所有的数据
    sql语句-->需指定返回值类型

<!-- 获取所有的班级信息 -->
<select id="getAllClasses" resultType="Clazz">
  select * from class1
</select>

    对应的方法

/**
 * 获取所有的班级
 */
public List<Clazz> getAllClasses() {
  SqlSession session = super.getSqlSession();
  return session.selectList("com.dao.IClassDao.getAllClasses");
}

4.删除

  删除分为:单条数据删除和多条数据删除
  类型一:单条数据删除
    sql语句-->需指定参数类型(默认返回int类型)

<!-- 删除学生信息 -->
<delete id="deleteStudentBysId" parameterType="int">
  delete from student1 where sId=#{sid}
</delete>

    对应的方法

/**
 * 删除学生信息
 */
public int deleteStudentBysId(int sId) { 
  SqlSession session = super.getSqlSession();
  return session.delete("com.dao.IStudentDao.deleteStudentBysId", sId);
}

  类型二:删除多条数据--未测试
    sql语句-->需指定参数类型(默认返回int类型)

<delete id = "delete" parameterType = "java.util.List"> 
  delete from tests where id in 
  <foreach collection="list" item = "item" open="(" separator="," close=")">
    #{item} 
  </foreach> 
</delete>

2024-08-15 10:03:30

5.mapper.xml和mapper.java

Mapper.xml

以mysql为例

<?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.xxx.base.service.plat.dao.PrivacySettingMapper">

    <resultMap id="BaseResultMap" type="com.xxx.base.plat.domain.PrivacySetting">
        <id property="id" column="ID" jdbcType="INTEGER"/>
        <result property="typeCode" column="TYPE_CODE" jdbcType="VARCHAR"/>
        <result property="typeName" column="TYPE_NAME" jdbcType="VARCHAR"/>
        <result property="typeValue" column="TYPE_VALUE" jdbcType="VARCHAR"/>
        <result property="typeContent" column="TYPE_CONTENT" jdbcType="VARCHAR"/>
        <result property="type" column="TYPE" jdbcType="VARCHAR"/>
        <result property="typeComing" column="TYPE_COMING" jdbcType="VARCHAR"/>
        <result property="settingType" column="SETTING_TYPE" jdbcType="VARCHAR"/>
        <result property="createTime" column="CREATETIME" jdbcType="TIMESTAMP"/>
        <result property="privacyType" column="PRIVACY_TYPE" jdbcType="VARCHAR"/>
        <result property="status" column="STATUS" jdbcType="VARCHAR"/>
    </resultMap>

    <sql id="Base_Column_List">
        ID,TYPE_CODE,TYPE_NAME,
        TYPE_VALUE,TYPE_CONTENT,TYPE,
        TYPE_COMING,SETTING_TYPE,CREATETIME,
        PRIVACY_TYPE,STATUS
    </sql>

    <select id="queryList" resultMap="BaseResultMap">
        select
            <include refid="Base_Column_List" />
        from privacy_setting T1
            <where>
                <if test="null != typeCode and '' != typeCode">and T1.TYPE_CODE = #{typeCode}</if>
                <if test="null != typeValue and '' != typeValue">and T1.TYPE_VALUE = #{typeValue}</if>
                <if test="null != typeName and '' != typeName">and T1.TYPE_NAME like concat('%', #{typeName}, '%')</if>
                <if test="null != type and '' != type">and T1.TYPE = #{type}</if>
            </where>
        order by T1.CREATETIME desc
    </select>

    <insert id="insert" useGeneratedKeys="true" keyColumn="ID" keyProperty="id">
        insert into privacy_setting
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="null != id">
                ID,
            </if>
            <if test="null != typeCode and '' != typeCode">
                TYPE_CODE,
            </if>
            <if test="null != typeName and '' != typeName">
                TYPE_NAME,
            </if>
            <if test="null != typeValue and '' != typeValue">
                TYPE_VALUE,
            </if>
            <if test="null != typeContent and '' != typeContent">
                TYPE_CONTENT,
            </if>
            <if test="null != type and '' != type">
                TYPE,
            </if>
            <if test="null != typeComing and '' != typeComing">
                TYPE_COMING,
            </if>
            <if test="null != settingType and '' != settingType">
                SETTING_TYPE,
            </if>
            <if test="null != privacyType and '' != privacyType">
                PRIVACY_TYPE,
            </if>
            <if test="null != createTime">
                CREATETIME,
            </if>
            <if test="null != status and '' != status">
                STATUS,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="null != id ">
                #{id},
            </if>
            <if test="null != typeCode and '' != typeCode">
                #{typeCode},
            </if>
            <if test="null != typeName and '' != typeName">
                #{typeName},
            </if>
            <if test="null != typeValue and '' != typeValue">
                #{typeValue},
            </if>
            <if test="null != typeContent and '' != typeContent">
                #{typeContent},
            </if>
            <if test="null != type and '' != type">
                #{type},
            </if>
            <if test="null != typeComing and '' != typeComing">
                #{typeComing},
            </if>
            <if test="null != settingType and '' != settingType">
                #{settingType},
            </if>
            <if test="null != privacyType and '' != privacyType">
                #{privacyType},
            </if>
            <if test="null != createTime">
                #{createTime},
            </if>
            <if test="null != status and '' != status">
                #{status},
            </if>
        </trim>
    </insert>

    <update id="update">
        update privacy_setting
        <set>
            <if test="null != typeCode and '' != typeCode">TYPE_CODE = #{typeCode},</if>
            <if test="null != typeName and '' != typeName">TYPE_NAME = #{typeContent},</if>
            <if test="null != typeValue and '' != typeValue">TYPE_VALUE = #{typeValue},</if>
            <if test="null != typeContent and '' != typeContent">TYPE_CONTENT = #{typeContent},</if>
            <if test="null != type and '' != type">TYPE = #{type},</if>
            <if test="null != typeComing and '' != typeComing">TYPE_COMING = #{typeComing},</if>
            <if test="null != settingType and '' != settingType">SETTING_TYPE = #{settingType},</if>
            <if test="null != privacyType and '' != privacyType">PRIVACY_TYPE = #{privacyType},</if>
            <if test="null != status and '' != status">STATUS = #{status},</if>
            <if test="null != createTime ">CREATETIME = #{createTime},</if>
        </set>
        where id = #{id}
    </update>

    <update id="updateStatus">
        update privacy_setting set STATUS = #{status}
        where id = #{id}
    </update>
	
    <delete id="delete">
        delete from privacy_setting
        where id = #{id}
    </delete>
</mapper>

Mapper.java

@DS("mysql")
public interface PrivacySettingMapper {
    /**
     * 分页查询
     */
    List<PrivacySetting> queryList(PrivacySettingRequest request);

    /**
     * 新增
     */
    int insert(PrivacySetting privacySetting);

    /**
     * 更新
     * @return int 影响行数
     */
    int updateStatus(PrivacySetting privacySetting);

    /**
     * 删除
     * @return int 影响行数
     */
    int delete(PrivacySetting privacySetting);

}

说明:

如果配置了多个数据源,可通过com.baomidou.dynamic.datasource.annotation.DS的注解

@DS("数据源名称")

2024-09-14 10:05:44

6.批量插入

主键由外部提供(如:Redis、雪花算法)

<insert id="insertWJ_PATIENT_DETAILINFO_RESULTManual" parameterType="java.util.List">
	INSERT INTO ZX_REPORT_FILE
		(ID, REPORT_URL, REPORT_IMG, REPORT_NAME, REPORT_TYPE)
    VALUES
    <foreach collection="list" item="i" separator=",">
		(#{i.id,jdbcType=VARCHAR},
		#{i.reportUrl,jdbcType=VARCHAR},
		#{i.reportImg,jdbcType=VARCHAR},
		#{i.reportName,jdbcType=VARCHAR},
		#{i.reportType,jdbcType=VARCHAR})
    </foreach>
</insert>
<insert id="insertRoleModuleList" parameterType="com.XXX.platform.api.rolemodule.domain.RoleModule">
	INSERT INTO base_ac_role_module
	(roleId,moduleId,isOper,isAuth) VALUES
	<foreach item="item" index="index" collection="roleModuleList" separator=",">
		(#{item.roleId},#{item.moduleId},#{item.isOper},#{item.isAuth})
	</foreach>
</insert>

主键使用uuid(mysql)

<insert id="insertWJ_PATIENT_DETAILINFO_RESULTManual" parameterType="java.util.List">
	INSERT INTO WJ_PATIENT_DETAILINFO_RESULT
		(DETAILINFO_RESULT_ID,ORG_CODE,PATIENT_TYPE,PATIENT_ID,APPLY_NO,REPORT_TYPE,REPORT_CONENT,REPORT_URL,CON_ORG_CODE)
    VALUES
    <foreach collection="list" item="t" separator=",">
		<![CDATA[
			(replace(uuid(), '-', ''),
			#{t.orgCode,jdbcType=VARCHAR},
			#{t.patientType,jdbcType=VARCHAR},
			#{t.patientId,jdbcType=VARCHAR},
			#{t.applyNo,jdbcType=VARCHAR},
			#{t.reportType,jdbcType=VARCHAR},
			#{t.reportConent,jdbcType=VARCHAR},
			#{t.reportUrl,jdbcType=VARCHAR},
			#{t.conOrgCode,jdbcType=VARCHAR})
		]]>
    </foreach>
</insert>

7.resultMap

BaseResultMap用于设定Java属性与表字段的一一对应关系。

<resultMap id="BaseResultMap" type="com.xxx.ycwj.api.lis.domain.WjPatientDetailinfoResult">
	<id column="detailinfo_result_id" jdbcType="VARCHAR" property="detailinfoResultId" />
    <result column="org_code" jdbcType="VARCHAR" property="orgCode" />
    <result column="patient_type" jdbcType="VARCHAR" property="patientType" />
    <result column="patient_id" jdbcType="VARCHAR" property="patientId" />
    <result column="apply_no" jdbcType="VARCHAR" property="applyNo" />
    <result column="examitem_code" jdbcType="VARCHAR" property="examitemCode" />
    <result column="examitem_name" jdbcType="VARCHAR" property="examitemName" />
    <result column="examitem_result" jdbcType="VARCHAR" property="examitemResult" />
    <result column="unit" jdbcType="VARCHAR" property="unit" />
    <result column="state" jdbcType="VARCHAR" property="state" />
    <result column="reference" jdbcType="VARCHAR" property="reference" />
    <result column="iswjz" jdbcType="VARCHAR" property="iswjz" />
    <result column="wjzjgz" jdbcType="VARCHAR" property="wjzjgz" />
    <result column="wjzckz" jdbcType="VARCHAR" property="wjzckz" />
    <result column="checkdoc_name" jdbcType="VARCHAR" property="checkdocName" />
    <result column="check_date" jdbcType="TIMESTAMP" property="checkDate" />
    <result column="reportdoc_name" jdbcType="VARCHAR" property="reportdocName" />
    <result column="report_date" jdbcType="TIMESTAMP" property="reportDate" />
    <result column="reviewdoc_name" jdbcType="VARCHAR" property="reviewdocName" />
    <result column="review_date" jdbcType="TIMESTAMP" property="reviewDate" />
    <result column="createtime" jdbcType="TIMESTAMP" property="createtime" />
    <result column="check_find" jdbcType="VARCHAR" property="checkFind" />
    <result column="check_point" jdbcType="VARCHAR" property="checkPoint" />
    <result column="reserve_field3" jdbcType="VARCHAR" property="reserveField3" />
    <result column="reserve_field4" jdbcType="VARCHAR" property="reserveField4" />
    <result column="report_type" jdbcType="VARCHAR" property="reportType" />
    <result column="sqdtype" jdbcType="VARCHAR" property="sqdtype" />
    <result column="report_url" jdbcType="VARCHAR" property="reportUrl" />
    <result column="report_conent" jdbcType="VARCHAR" property="reportConent" />
    <result column="report_name" jdbcType="LONGVARCHAR" property="reportName" />
    <result column="con_org_code" jdbcType="VARCHAR" property="conOrgCode" />
    <result column="report_file_id" jdbcType="VARCHAR" property="reportFileId" />
    <result column="sample_id" jdbcType="VARCHAR" property="sampleId" />
    <result column="sample_type_name" jdbcType="VARCHAR" property="sampleTypeName" />
    <result column="send_time" jdbcType="TIMESTAMP" property="sendTime" />
    <result column="sender" jdbcType="VARCHAR" property="sender" />
</resultMap>

ResultMapWithBLOBs可以继承BaseResultMap。

<resultMap extends="BaseResultMap" id="ResultMapWithBLOBs" type="com.xxx.ycwj.api.lis.domain.WjPatientDetailinfoResult">
	<result column="report_img" jdbcType="LONGVARCHAR" property="reportImg" />
</resultMap>

8.关于sql的复用

关于表字段的复用

<sql id="Base_Column_List">
    detailinfo_result_id, org_code, patient_type, patient_id, apply_no, examitem_code,
    examitem_name, examitem_result, unit, state, reference as reference, iswjz, wjzjgz, wjzckz, checkdoc_name,
    check_date, reportdoc_name, report_date, reviewdoc_name, review_date, createtime,
    check_find, check_point, reserve_field3, reserve_field4, report_type, sqdtype, report_url,report_name,
    report_conent, con_org_code, report_file_id,sample_id,sample_type_name,send_time,sender
</sql>

关于查询条件的复用

<sql id="WJ_PATIENT_DETAILINFO_RESULT_WHERE">
    <where>
      <if test="DETAILINFO_RESULT_ID != null and DETAILINFO_RESULT_ID !=''">
        and T.DETAILINFO_RESULT_ID = #{DETAILINFO_RESULT_ID}
      </if>
      <if test="ORG_CODE != null and ORG_CODE !=''">
        and T.ORG_CODE = #{ORG_CODE}
      </if>
      <if test="PATIENT_TYPE != null and PATIENT_TYPE !=''">
        and T.PATIENT_TYPE = #{PATIENT_TYPE}
      </if>
      <if test="PATIENT_ID != null and PATIENT_ID !=''">
        and T.PATIENT_ID = #{PATIENT_ID}
      </if>
      <if test="APPLY_NO != null and APPLY_NO !=''">
        and T.APPLY_NO = #{APPLY_NO}
      </if>
      <if test="EXAMITEM_CODE != null and EXAMITEM_CODE !=''">
        and T.EXAMITEM_CODE = #{EXAMITEM_CODE}
      </if>
      <if test="STATE != null and STATE !=''">
        and T.STATE = #{STATE}
      </if>
      <if test="CHECK_DATE != null and CHECK_DATE !=''">
        and  T.CHECK_DATE = str_to_date(#{CHECK_DATE},'%Y-%m-%d')
      </if>
      <if test="REPORT_DATE != null and REPORT_DATE !=''">
        and T.REPORT_DATE = str_to_date(#{REPORT_DATE},'%Y-%m-%d')
      </if>
      <if test="REVIEW_DATE != null and REVIEW_DATE !=''">
        and T.REVIEW_DATE = str_to_date(#{REVIEW_DATE},'%Y-%m-%d')
      </if>
      <if test="CREATETIME != null and CREATETIME !=''">
        and T.CREATETIME = str_to_date(#{CREATETIME},'%Y-%m-%d')
      </if>
      <if test="REPORT_TYPE != null and REPORT_TYPE !=''">
        and T.REPORT_TYPE = #{REPORT_TYPE}
      </if>
      <if test="CON_ORG_CODE != null and REPORT_TYPE !=''">
        and T.CON_ORG_CODE = #{CON_ORG_CODE}
      </if>
    </where>
</sql>

调用 

<select id="getWJ_PATIENT_DETAILINFO_RESULT" resultMap="ResultMapWithBLOBs">
    select 
		<include refid="Base_Column_List" />
    from wj_patient_detailinfo_result T
    <include refid="WJ_PATIENT_DETAILINFO_RESULT_WHERE" />
</select>

另外一种用法

<select id="getWJ_TEST_SAMPLE_TYPE"  resultMap="ResultMapWithBLOBs">
    select 
		<include refid="Base_Column_List" />
		,
		<include refid="Blob_Column_List" />
    from wj_test_sample_type t
    <include refid="WJ_TEST_SAMPLE_TYPE_WHERE"/>
</select>

9.in()

第1种方式

<select id="getApplyNo" parameterType="map" resultType="java.util.Map" >
    SELECT 
		T.APPLY_NO
    FROM WJ_CONSULT_INFO T
    WHERE T.ORG_CODE = #{ORG_CODE}
      AND T.CONSULT_STATUS != '-1'
      AND (T.APPLY_DATE BETWEEN str_to_date(#{begin}, '%Y-%m-%d') AND str_to_date(#{end}, '%Y-%m-%d 23:59:59'))
      AND T.APPLY_NO IN
      <foreach item="n" collection="APPLY_NO" open="(" separator="," close=")">
        #{n}
      </foreach>
</select>

2024-10-14 11:27:56

第2种方式:

in()里面可以使用select。

<select id="queryFistName" resultType="com.xyhsoft.platform.api.questionnaire.domain.ArrangeTemplateClassify">
	select classify_name AS "classifyName",first_classify_id AS "firstClassifyId" from base_arrange_template_classify
	where is_delete = 0 and second_classify_id is  null
	and first_classify_id in
	(
		select distinct first_classify_id from base_arrange_template_classify
		where second_classify_id is not null and is_delete = 0
		<if test="extField1 != null and extField1 != ''">
			and typet = #{extField1}
		</if>
	)
</select>

10.开始时间和结束时间

前提:

参数开始时间和结束时间都是字符串类型

2024-10-24 16:08:32

MYSQL

关于日期的比较,mysql有两种实现方式

第1种:

将要查询的日期字符串转日期。

方式1又需要分情况讨论

如果是只比较日期,不比较时间,使用下面这个sql。

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[  AND wci.APPLY_DATE >= str_to_date(#{beginDate},'%Y-%m-%d')]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE <= STR_TO_DATE(CONCAT(#{endDate}, ' 23:59:59'), '%Y-%m-%d %H:%i:%s') ]]>
</if>

说明:

这个时候,入参beginDate和endDate是字符串类型,并且只包含日期。

如果不仅需要比较日期,还需要比较时间,须用下面这个: 

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[  AND wci.APPLY_DATE >= str_to_date(#{beginDate},'%Y-%m-%d %H:%i:%s')]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE <= STR_TO_DATE(#{endDate}, '%Y-%m-%d %H:%i:%s') ]]>
</if>

说明:

这个时候,入参beginDate和endDate是字符串类型,不仅包含日期还包含时间。

第2种:(推荐使用)

将要查询的日期字符串转日期并往后推1天。

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[  AND wci.APPLY_DATE >= str_to_date(#{beginDate},'%Y-%m-%d')]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE < DATE_ADD(STR_TO_DATE(#{endDate}, '%Y-%m-%d'), INTERVAL 1 DAY) ]]>
</if>

说明:

使用interval N day时,数字N可以使用单引号包裹住,也可以不使用单引号包裹。

第3种:

在mysql中,日期类型可以和日期字符串直接作比较。

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[  AND wci.APPLY_DATE >= #{beginDate} ]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE <= concat(#{endDate},' 23:59:59') ]]>
</if>

oracle

在oracle中,日期与字符串不能作比较。 

方式1

如果是只比较日期,不比较时间,使用下面这个sql。

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[ AND wci.APPLY_DATE >= TO_DATE(#{beginDate},'YYYY-MM-DD') ]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE <= TO_DATE(#{endDate} || ' 23:59:59', 'YYYY-MM-DD HH24:MI:SS') ]]>
</if>

说明:

这个时候,入参beginDate和endDate是字符串类型,并且只包含日期。

如果不仅需要比较日期,还需要比较时间,须用下面这个: 

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[ AND wci.APPLY_DATE >= TO_DATE(#{beginDate},'YYYY-MM-DD HH24:MI:SS') ]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE <= TO_DATE(#{endDate}, 'YYYY-MM-DD HH24:MI:SS') ]]>
</if>

我们可以看到:

开始时间在比较时,只设置了日期,没有设置时间,那是因为:当日期没有设置时间时,默认就是0时0分0秒,相当于:

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[ AND wci.APPLY_DATE >= TO_DATE(#{beginDate} || ' 00:00:00', 'YYYY-MM-DD HH24:MI:SS') ]]>
</if>

方式2(推荐使用)

往后推一天

<if test="beginDate !=null and beginDate !=''">
  <![CDATA[ AND wci.APPLY_DATE >= TO_DATE(#{beginDate},'YYYY-MM-DD') ]]>
</if>
<if test="endDate !=null and endDate !=''">
  <![CDATA[ AND wci.APPLY_DATE < TRUNC(TO_DATE(#{endDate}, 'YYYY-MM-DD')) + INTERVAL '1' DAY ]]>
</if>

说明:

使用interval 'N' day时,数字N必须使用单引号包裹住,否则会报错。

11.查询当天数据

mysql

<![CDATA[
    and base_eva_detail.create_time >=  CURDATE()
    and base_eva_detail.create_time < CURDATE() + INTERVAL 1 DAY
]]>    

oracle

<![CDATA[
	and base_eva_detail.create_time >= TRUNC(SYSDATE)
	and base_eva_detail.create_time <= TRUNC(SYSDATE) + INTERVAL '1' DAY
]]>

11.查询指定日期的数据

mysql

<if test="CONSULT_DATE !=null and CONSULT_DATE !=''">
	and (T.CONSULT_DATE BETWEEN STR_TO_DATE(concat(#{CONSULT_DATE}, ' 00:00:00'),'%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(concat(#{CONSULT_DATE}, ' 23:59:59'),'%Y-%m-%d %H:%i:%s')
</if>

oracle

<if test="CONSULT_DATE !=null and CONSULT_DATE !=''">
	and (T.CONSULT_DATE BETWEEN TO_DATE(concat(#{CONSULT_DATE}, ' 00:00:00'),'YYYY-MM-DD HH24:MI:SS') AND TO_DATE(concat(#{CONSULT_DATE}, ' 23:59:59'),'YYYY-MM-DD HH24:MI:SS')
</if>

不管是mysql还是ORCLE,都还有一种实现方式:

那就是,在查询的时候,直接将对日期字段进行格式化。

但并不推荐这样用,这样会影响查询速度。

因为:每次执行查询时都需要对每一行数据调用该函数,这会增加计算开销。

 

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2017-03-09 17:52  Marydon  阅读(334)  评论(0编辑  收藏  举报