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

时间:2021-12-24 09:22:24

1.因为在向动态表中插入数据后,要返回主键id,所以我建了实体类。(若是不需要返回主键,则不需要建实体类)

xml代码

 <insert id="insertInfo" parameterType="com.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>

①若是不需要返回插入数据的主键id,则 parameterType="java.util.Map"即可,无需建实体类

②需要返回主键id的,实体类如下

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

2.向动态表名,动态属性表中更新数据

<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>