欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis向动态表名,动态属性表中插入数据,更新数据

程序员文章站 2022-04-22 08:32:48
...

1、在向动态表中插入数据后,要返回主键id,需要建实体类。(若是不需要返回主键,则不需要建实体类)

package com.lyf.entity

public class InsertMao{
    //主建
	private int id;
	//表名
	private String tableName;
	//字段和字段值
	private Map<String,String> params;
}

新增sql: 

 <insert id="insertInfo" parameterType="package com.lyf.entity.InsertMap" useGeneratedKeys="true" keyProperty="id">  
     insert ignore into ${tableName}   
      <foreach collection="params.keys" item="key" open="(" close=")" separator="," >  
         ${key} 
      </foreach>  
      values   
      <foreach collection="params.keys"  item="key" open="(" close=")" separator=",">  
         #{params.${key}}  
      </foreach>  
</insert>

更新sql:

<update id="updateInfoByID" parameterType="java.util.Map">
  UPDATE ${tableName} set
      <foreach item="value" index="key" collection="params" separator=",">
         <if test="key != 'id'">
              ${key} = #{value}
         </if>
      </foreach>
       WHERE
     <foreach item="value" index="key" collection="params" separator=",">
           <if test="key == 'id'">
               ID = #{value}
           </if>
     </foreach> 
</update>

 

相关标签: Mybatis java