mysql使用XML实现增删改查模板(参数形式包括:String、对象、集合、数组、Map)

导读:本篇文章讲解 mysql使用XML实现增删改查模板(参数形式包括:String、对象、集合、数组、Map),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

在这里插入图片描述

说明:方便后续根据场景直接拷贝代码

一、foreach 标签的属性含义

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
foreach元素的属性主要有 item,index,collection,open,separator,close。
item集合中每一个元素进行迭代时的别名,
index表示在迭代过程中,每次迭代到的位置,
open该语句以什么开始,
separator在每次进行迭代之间以什么符号作为分隔 符,
close以什么结束,
在使用foreach的时候最关键的也是最容易出错的就是collection属性,
该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,
主要有一下3种情况:

  1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    
  2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    
  3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了
    

二、使用注意事项

注意点1:条件判断使用if标签
数值型使用:<if test="phone != null  and phone != 0">phone,</if>
字符串使用:<if test="name != null  and name != ''">ip,</if>
注意点2:${schema} 中$充当占位符,可以用来输入租户名
注意点3:<foreach>标签在使用中有两种形式
形式1:<foreach item="item" collection="arr" separator="," open="(" close=")" index="">
形式2:<foreach collection="conditionMap.keys" item="item" index="index" separator="and">
注意点4:有的 index="",有的index="index",这个我没测试过,是不是只要不用这个index属性,设置哪种都不影响?
注意点5:形参是list、array、map 时,在具体使用<foreach>标签时解析方式都不太一样,需要留意。

三、CRUD模板

1.查询

语法:SELECT * FROM table_name;

1.1根据条件id数组查询集合:(传参1为数组,形参1为String)

List<MailConfig> getListByIdArr(@Param("arr") String[] arr, @Param("schema") String schema);

<select id="getListByIdArr" resultMap="BaseResultMap">
	SELECT * FROM ${schema}.poc_grp_user 
	WHERE
	group_id in
	<foreach item="item" collection="arr" separator="," open="(" close=")" index="">
		#{item}
	</foreach>
</select>

1.2根据条件Map查询集合:(传参1为对象,形参1为Map)

List<Map<String,String>> queryByCondition(@Param("moModel") MoModel moModel, @Param("conditionMap") Map<String, String> conditionMap);

<select id="queryByCondition" resultType="map">
	select * from `${moModel.tableName}` 
	<where> 
		<foreach collection="conditionMap.keys" item="item" index="index" separator="and">
			 ${item}=#{conditionMap.${item}}
		</foreach>
	</where>  
</select>

1.3根据条件neid查询集合:(传参为对象)

List<Map<String,String>> queryAllByNeIdAndMoName(MoModel moModel);  

<select id="queryAllByNeIdAndMoName" parameterType="com.hero.lte.ems.config.entity.MoModel" resultType="map">
	select * from `${tableName}` where neid=#{neId}
</select>

2.新增

语法: 第一种形式无需指定要插入数据的列名,只需提供被插入的值即可:
INSERT INTO table_name VALUES (value1,value2,value3,…);

第二种形式需要指定列名及被插入的值:
INSERT INTO table_name (column1,column2,column3,…) VALUES (value1,value2,value3,…);

2.1单条新增:(传参为对象)

int insert(MailConfig entity);
		
<!--新增返回主键ID-->
<insert id="insert" parameterType="com.hero.nms.platform.system.model.MailConfig" >
	<selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE" >
		SELECT nextval('seq_mail_config_id'::regclass) AS id	//第一种写法
		//SELECT LAST_INSERT_ID()	//第二种写法
	</selectKey>
	insert into smconfig_mail
	<trim prefix="(" suffix=")" suffixOverrides=",">
		id,
		<if test="phone != null  and phone != 0">phone,</if>
		<if test="name != null  and name != ''">ip,</if>
	</trim>
	<trim prefix="values (" suffix=")" suffixOverrides=",">
		#{id},
		<if test="phone != null  and phone != 0">#{phone},</if>
		<if test="name != null  and name != ''">#{name},</if>      
	</trim>
</insert>

2.2批量新增:(传参1为对象,传参2为Map)

int addMoByAttr(@Param("moModel") MoModel moModel, @Param("attrMap") Map<String, String> attrMap);

<insert id="addMoByAttr">
	insert into `${moModel.tableName}`
	<foreach collection="attrMap.keys" item="key" index="index" open="(" separator="," close=")">
		 ${key}
	 </foreach>
		values
	 <foreach collection="attrMap.keys" item="key" index="index" open="(" separator="," close=")">
		 #{attrMap.${key}}
	 </foreach>
</insert>

2.3批量新增:(传参为集合)

void batchInsertService(@Param("logicalTopos") List<LogicalTopo> logicalTopos);
	
<insert id="batchInsertService" keyProperty="id" useGeneratedKeys="true">
	<selectKey resultType="java.lang.Integer" keyProperty="id" order="BEFORE" >
		SELECT LAST_INSERT_ID()	
	</selectKey>
       insert into logical_topo ( service_id ,x,y ) values
       <foreach collection='logicalTopos' item='item' index='index ' separator=', '>
           (#{item.serviceId}, #{item.x}, #{item.y} )
       </foreach>
   </insert>

3.修改

语法:UPDATE table_name SET column1=value1,column2=value2 WHERE some_column=some_value;

3.1批量更新:(传参为集合)

void batchUpdateInstance(@Param("logicalTopos") List<LogicalTopo> logicalTopos);
	
<update id="batchUpdateInstance">
      <foreach collection='logicalTopos' item='item' index='index' separator='; '>				
          update logical_topo 
		<set>
			<if test="x != null  and x != 0">x=#{item.id},</if>
			<if test="y != null  and y != ''">y=#{item.name},</if>
		</set>	
		where 1=1
			<if test="user_id != null  and user_id != 0">AND user_id=#{item.userId}</if>						
      </foreach>
</update>

3.2批量更新:(传参1为对象,传参2为Map)

int updateByCondition(@Param("moModel") MoModel moModel, @Param("attrMap") Map<String, String> attrMap);
	
<update id="updateByCondition">
 	update `${moModel.tableName}`
	<set>      
		 <foreach collection="attrMap.keys" item="key" index="index" separator=",">
			 ${key}
		 </foreach>       
	</set> 
	<where> 
		<foreach collection="attrMap.keys" item="key" index="index" separator="and">
			 ${key}=#{attrMap.${${key}}}
		</foreach>
	</where>     
</update>

3.3单条更新:(传参为对象)

void modifyPwd(@Param("account")Account account);
	
<update id="modifyPwd" parameterType="com.hero.nms.pl.security.domain.Account">
       update t_user
       <set>
           <if test="account.password!=null and account.password!=''">
               password = #{account.password},
           </if>           
       </set>
       where username = #{account.username}
   </update>

4.删除

语法: DELETE FROM table_name WHERE some_column=some_value;

4.1批量删除:(传参1为对象,传参2为Map)

int deleteByCondition(@Param("moModel") MoModel moModel, @Param("conditionMap") Map<String, String> conditionMap);
	
<deleteid="deleteByCondition">
	delete from `${moModel.tableName}`
	<where> 
	    <foreach collection="conditionMap.keys" item="item" index="index" separator="and">
	         ${item}=#{conditionMap.${item}}
	    </foreach>
   	</where> 
</delete>

4.2根据条件nid删除一条:(传参为对象)

int deleteAllByNeIdAndMoName(MoModel moModel);
	
<delete id="deleteAllByNeIdAndMoName" parameterType="com.hero.lte.ems.config.entity.MoModel">
	delete from `${tableName}` where neid=#{neId}
</delete>

4.3批量删除:传参1为String,传参2为集合)

int batchDelete(@Param("table") String table, @Param("list") List<EntryInfo> list);
	
<delete id="batchDelete">
       DELETE FROM nms.${table}
       WHERE key IN
       <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
           #{item.key}
       </foreach>
   </delete>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/106224.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!