您好,登錄后才能下訂單哦!
mapper.xml 中共用
mapper.xml 間共用
項目中也許我們會遇到一段sql語句被多個查詢、增加等語句用到的情況,如何去偷懶呢,復用sql無疑是較好的選擇
這里只提供簡單的示范:
如果只是單表查詢,并且希望共用的sql只會出現在同一個mapper.xml文件中,那么我們可以直接在
<mapper namespace="XXXXX"></mapper>
中寫下面的業務代碼
<sql id="unitSql"> a.userId,a.legalCode,legalName, bidderCodeType,legalRole, licenseNo,DATE_FORMAT(licenseEndDate,"%Y-%m-%d") AS licenseEndDate, taxCertNo,DATE_FORMAT(taxCertEndDate,"%Y-%m-%d") AS taxCertEndDate, localTaxCertNo,DATE_FORMAT(localTaxCertEndDate,"%Y-%m-%d") AS localTaxCertEndDate, organNo,DATE_FORMAT(organCertEndDate,"%Y-%m-%d") AS organCertEndDate, legalRepresent,legalType, perresentPhone,legalIndustary,creditRate, countryRegion,legalUnitAddress,regionCode,registerProvince, a.regCapital,a.regCapCurRency,a.regUnit, registerCity,registerCounty,basicBank,basicBranchBank, basicAccountNo,basicAccountName,legalContact,legalContactPhone, legalContactAddress,legalWeb,legalZipCode,legalEmail, legalStatus </sql>
然后引用
<select id="getTenderAgentById" parameterType="String" resultType="Map"> select <include refid="unitSql"/>, -- 就是這句話引用 ,refid為共有sql語句id b.auditOpinion,b.createUser, b.createTime, b.lastUpdateUser, b.lastUpdateTime, b.disabled,b.infoStatus from P_legalUnit a, P_tenderAgent b where b.userId=#{userId} AND a.userId = b.userId AND b.disabled='0' </select>
如果是連表查詢,那么我們極有可能會希望有一個sql語句被多個mapper.xml引用的的方法,很簡單。
我們可以新建一個mapper.xml文件(當然,這個mapper.xml要在你的掃描路徑下,本文不贅述)。取名為common.xml
該文件內容為
<?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="common"> <sql id="common.unitSql"> a.userId,a.legalCode,legalName, bidderCodeType,legalRole, licenseNo,DATE_FORMAT(licenseEndDate,"%Y-%m-%d") AS licenseEndDate, taxCertNo,DATE_FORMAT(taxCertEndDate,"%Y-%m-%d") AS taxCertEndDate, localTaxCertNo,DATE_FORMAT(localTaxCertEndDate,"%Y-%m-%d") AS localTaxCertEndDate, organNo,DATE_FORMAT(organCertEndDate,"%Y-%m-%d") AS organCertEndDate, legalRepresent,legalType, perresentPhone,legalIndustary,creditRate, countryRegion,legalUnitAddress,regionCode,registerProvince, a.regCapital,a.regCapCurRency,a.regUnit, registerCity,registerCounty,basicBank,basicBranchBank, basicAccountNo,basicAccountName,legalContact,legalContactPhone, legalContactAddress,legalWeb,legalZipCode,legalEmail, legalStatus </sql> </mappper>
在另一個mapper.xml文件引用
<select id="getTenderAgentById" parameterType="String" resultType="Map"> select <include refid="common.unitSql"/>, -- 就是這句話引用 ,refid為共有sql語句id b.auditOpinion,b.createUser, b.createTime, b.lastUpdateUser, b.lastUpdateTime, b.disabled,b.infoStatus from P_legalUnit a, P_tenderAgent b where b.userId=#{userId} AND a.userId = b.userId AND b.disabled='0' </select>
==注:為何我的文件名要取為common.xml并且id也為common.unitSql呢?這是為了后期維護方便,如此,可以更容易找到該共有的sql在哪一個文件==
以上所述是小編給大家介紹的Mybatis中 SQL語句復用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。