mybatis中一些sql語法使用方法

在mybatis中的mapper中使用批量添加,這裏針對mysql與oracle是有所區別的

在Oracle數據庫

<!-- 批量添加 -->
  <insert id="insertyygetparts" parameterType="java.util.List">
  insert into C##TRAIN.YY_GETPARTS (ID, COMPONENTCATALOGID, COMPONENTCATALOGNAME, 
      USERID, USERNAME, WAREHOUSEID, 
      WAREHOUSENAME, NUM) 
      <foreach collection="list" item="YyGetparts" index="index" open="(" separator="union all" close=")">
      SELECT
      #{YyGetparts.id, jdbcType=VARCHAR},
      #{YyGetparts.componentcatalogid},
      #{YyGetparts.componentcatalogname},
      #{YyGetparts.userid},
      #{YyGetparts.username},
      #{YyGetparts.warehouseid},
      #{YyGetparts.warehousename},
      #{YyGetparts.num}
      from dual
      </foreach>
  </insert>

在mysql數據庫

 <!-- 批量添加 -->
  <insert id="insertyygetparts" parameterType="java.util.List">
  insert into C##TRAIN.YY_GETPARTS (ID, COMPONENTCATALOGID, COMPONENTCATALOGNAME, 
      USERID, USERNAME, WAREHOUSEID, 
      WAREHOUSENAME, NUM) 
      <foreach collection="list" item="YyGetparts" index="index" separator=",">
      #{YyGetparts.id, jdbcType=VARCHAR},
      #{YyGetparts.componentcatalogid},
      #{YyGetparts.componentcatalogname},
      #{YyGetparts.userid},
      #{YyGetparts.username},
      #{YyGetparts.warehouseid},
      #{YyGetparts.warehousename},
      #{YyGetparts.num}
      </foreach>
  </insert>

在批量刪除上mysql與oracle是一樣的

<!-- 批量刪除 -->
  <delete id="deleteYyGetparts" parameterType="java.util.List">
  delete from C##TRAIN.YY_GETPARTS 
  where id in 
  <foreach collection="list" item="id"  index="index" open="(" separator="," close=")">
  #{id}
  </foreach>
  </delete> 

 

在mysql使用in方法查詢

<if test="catalogName != null">
  AND bd.catalog_name in 
  <foreach item="catalogName" index="index" collection="catalogName" open="(" separator="," close=")">
  #{catalogName}
  </foreach>
  </if>

 

foreach元素的屬性主要有 item,index,collection,open,separator,close。

    item表示集合中每一個元素進行迭代時的別名,
    index指 定一個名字,用於表示在迭代過程中,每次迭代到的位置,
    open表示該語句以什麼開始,
    separator表示在每次進行迭代之間以什麼符號作爲分隔 符,

    close表示以什麼結束。


#因爲mysql中沒有提供一次性更新多條數據的sql語句,但是我們可以轉換爲別的方式更新
update ly_shop_product 

set PonitPrice_ = 
case 
when Id_ =1 then 800
when Id_ =2 then 700
when Id_ =3 then 600
where 
Id_  = in (1,2,3)

#將上面的語句轉換爲mybati的語法就可以實現
<!--  這裏是測試mybatis中的批量導入  -->
#導入的方式用List集合導入,
<!-- 導入方式的批量更新 -->
  <update id="updateByForeach" parameterType="java.util.List" >
    update ly_shop_product
    <trim prefix="set" suffixOverrides=",">
        <trim prefix="PonitPrice_ = case" suffix="end,">
            <foreach collection="list" item="item" index="index">
                    <if test="item.ponitprice != null">
                     when Id_=#{item.id} then #{item.ponitprice}
                    </if>
            </foreach>
         </trim>
    </trim>
     where
     <foreach collection="list" separator="or" item="item" index="index" >
       Id_=#{item.id}
   </foreach>
  </update>

 

在mybatis的mapper.xml中${name}與#{name}的區別和使用場景

使用佔位符#{}可以有效防止sql注入,在使用時不需要關係參數值的類型,mybatis會自動進行JAVA類型和JDBC類型的裝換。說的通俗一點,當我們使用#{}的時候,產生的sql,#{}代表的內容會自動的添加上''。

例子:

    <select id="selectByParmName" resultMap="BaseResultMap" parameterType="hashmap">
  	select <include refid="Base_Column_List"></include>
  	from bus_parm 
  	<where>
  		<if test="parmName != null">
  			AND parm_name = #{parmName}
  		</if>
  	</where>
  </select>	select <include refid="Base_Column_List"></include>
  	from bus_parm 
  	<where>
  		<if test="parmName != null">
  			AND parm_name = #{parmName}
  		</if>
  	</where>
  </select>
生成的sql: select * from bus_parm where parm_name='2222'

使用佔位符${}可以將parameterType傳入的內容拼接在sql中且不進行JDBC類型轉換,不能防止sql注入。通俗一點就是,當我們使用${}的時候,產生的sql,${}代表的內容不會自動添加引號,傳入的十什麼就是什麼。

例子:

<select id="selectByParmName" resultMap="BaseResultMap" parameterType="hashmap">  
    select <include refid="Base_Column_List"></include>
  	from bus_parm 
  	<where>
  		<if test="parmName != null">
  			AND parm_name like '%${parmName}%'
  		</if>
  	</where>
</select>
生成的sql:select * from bus_parm where parm_name like '%22%'bus_parm where parm_name like '%22%'

 

在mysql和mybatis使用or和and連用的例子

sql中的語句,實現的就是在 clxxz_id或ldzcz_id或gongzhang_id或zljcy_id或yanshouyuan_id的id等於1並且時間在20180329和20180502之間。

select * from lund_maintain 
WHERE 
(clxxz_id = '1' OR 
ldzcz_id = '1' OR 
gongzhang_id = '1' OR 
zljcy_id = '1' OR 
yanshouyuan_id = '1' )
AND Date(CreateTime) >= '2018-03-29' 
AND Date(CreateTime) <= '2018-05-02' 
order by CreateTime desc

轉化成mapper

<select id="selectSignature" resultMap="BaseResultMap" parameterType="hashmap">
  	select <include refid="Base_Column_List"></include>
  	from lund_maintain
  	<where>
  		<if test="stateType == 1">
  			<trim prefix="(" suffix=")" prefixOverrides="OR" >
				<if test="userId != null">
	  				OR clxxz_id = #{userId}
	  			</if>
	  			<if test="userId != null">
	  				OR ldzcz_id = #{userId}
	  			</if>
	  			<if test="userId != null">
	  				OR gongzhang_id = #{userId}
	  			</if>
	  			<if test="userId != null">
	  				OR zljcy_id = #{userId}
	  			</if>
	  			<if test="userId != null">
	  				OR yanshouyuan_id = #{userId}
	  			</if>
  			</trim>
  		</if>
  		<if test="beginTime != null">
	  		AND Date(CreateTime) >= #{beginTime,jdbcType=TIMESTAMP}
	  	</if>
	  	<if test="endTime != null">
	  		AND Date(CreateTime) <![CDATA[<=]]> #{endTime,jdbcType=TIMESTAMP}
	  	</if>
  	</where>
  	order by CreateTime desc
  </select>

需要注意事項:
這裏講解trim標籤的幾個屬性:
prefix:前綴,指的是trim內容最開開始位置
suffix:後綴,指的是trim內容結束後添加
prefixoverride:去掉trim內容第一個出現的內容
suffixoverride:去掉trim最後一次出現的內容
在mybatis使用時候,我們使用trim標籤後,trim和where標籤一同使用這裏需要自己取消where後的第一個條件前的AND或者OR因爲這個時候where標籤自動去掉第一個條件前的AND功能失效

 

 

Mysql的一個查詢用法:

例子:現在有score表,和deduction表,score是一個人員成績表,deduction是一個成績範圍內減去分數的表,我們需要查詢出來成績表的所有記錄,並且用score的個人成績去匹配deduction表的成績範圍,添加這個個人成績應該減去的分值。

下面是score表

CREATE TABLE `score`  (
  `ID_` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '職工考試管理',
  `score_` int(3) NULL DEFAULT NULL COMMENT '個人成績',
  `create_User_ID_` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '創建用戶的ID',
  `create_User_Real_Name_` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '創建用戶的真實姓名',
  `create_Time_` datetime(0) NULL DEFAULT NULL COMMENT '創建時間',
  `desc` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '備註',
  `default_select_` int(1) NULL DEFAULT NULL,
  PRIMARY KEY (`ID_`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

 

下面是deduction表

CREATE TABLE `deduction`  (
  `ID_` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '績效考覈》職工考試減分設置',
  `score_min_` int(3) NULL DEFAULT NULL COMMENT '成績範圍最小分',
  `score_max_` int(3) NULL DEFAULT NULL COMMENT '成績範圍的最大分',
  `minus_score_` int(2) NULL DEFAULT NULL COMMENT '減去的分值',
  `create_User_ID_` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '創建用戶ID',
  `create_User_Real_Name_` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '創建用戶的真實姓名',
  `create_Time_` datetime(0) NULL DEFAULT NULL COMMENT '創建時間',
  `desc_` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '備註',
  `default_select_` int(1) NULL DEFAULT NULL,
  PRIMARY KEY (`ID_`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

 

下面使我們SQL

SELECT score.* ,
	( SELECT deduction.minus_score_ FROM deduction 
		WHERE 
			(score.score_ >= deduction.score_min_ 
		AND 
			score.score_ <= deduction.score_max_ )
	) AS jianfengScore 
FROM
	score 

 

發佈了46 篇原創文章 · 獲贊 22 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章