mybatis之sql标签与include标签

UDAL 不支持自定义函数,可以用mybatis中的sql标签进行改造替换

MyBatis中sql标签定义SQL片段,
include标签引用,可以复用SQL片段

sql标签中id属性对应include标签中的refid属性。通过include标签将sql片段和原sql片段进行拼接成一个完整的sql语句进行执行。

<sql id="sqlid">
    res_type_id,res_type
</sql>

<select id="selectbyId" resultType="com.property.vo.PubResTypeVO">
    select
    <include refid="sqlid"/>
    from pub_res_type
</select>
  • 引用同一个xml中的sql片段
<include refid="sqlid"/>
  • 引用公用的sql片段
<include refid="namespace+sqlid"/>

include标签中也可以用property标签,用以指定自定义属性。在sql标签中通过${}取出对应的属性值。

<select id="queryPubResType" parameterType="com.property.vo.PubResTypeVO" resultMap="PubResTypeList">
    select  a.res_type_id,
    <include refid="com.common.dao.FunctionDao.SF_GET_LNG_RES_TYPE">
        <property name="AI_RES_TYPE_ID" value="a.res_type_id"/>
        <property name="lng" value="#{lngId}"/>
    </include> as res_type
    from    pub_res_type a
</select>

定义一个公用的sql标签,用databaseId来区分不同数据库类型

<?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.common.dao.FunctionDao">
    <sql id="SF_GET_LNG_RES_TYPE" databaseId="oracle">
        SF_GET_LNG_RES_TYPE(${AI_RES_TYPE_ID}, ${lng})
    </sql>
    <sql id="SF_GET_LNG_RES_TYPE" databaseId="mysql">
        CASE WHEN ${AI_RES_TYPE_ID}=101 THEN
            CASE WHEN ${lng} = 1 THEN '男' ELSE 'male' END
        CASE WHEN ${AI_RES_TYPE_ID}=102 THEN
            CASE WHEN ${lng} = 1 THEN '女' ELSE 'female' END
        ELSE  ''
        END
    </sql>
</mapper>

改造之前,是调用数据库中的函数

<select id="queryPubResType" parameterType="com.property.vo.PubResTypeVO" resultMap="PubResTypeList">
    select  a.res_type_id,
    SF_GET_LNG_RES_TYPE(a.res_type_id, #{lngId}) as res_type
    from pub_res_type a
</select>

猜你喜欢

转载自www.cnblogs.com/Joyce-marmot/p/10884910.html
今日推荐