MyBatis中SQL的一些操作

252 阅读1分钟

传入一个List集合的update、insert处理

传入参数:List

<insert id="initSqlDimensionTable" parameterType="indi.wgx.pojo.SqlDimension">
    insert ignore into sql_dimension(dimension_id, execution_id, execution_field, rows_num, value, field_score)
    values
    <foreach collection="list" item="item" index="index" separator="," >
        (#{item.dimensionId}, #{item.executionId}, #{item.executionField}, #{item.rowsNum}, #{item.value}, #{item.fieldScore})
    </foreach>
</insert>

传入参数:List

<update id="updateAllScore" parameterType="java.util.List">
        <foreach collection="list" separator=";" item="res">
            update sql_dimension set field_score = #{res.fieldScore} where dimension_id = #{res.dimensionId}
        </foreach>;
        <foreach collection="list" separator=";" item="res">
            update sql_execution set content_score = #{res.contentScore}, time_score= #{res.timeScore} where execution_id = #{res.executionId}
        </foreach>;
        <foreach collection="list" separator=";" item="res">
            update sql_template set template_score = #{res.templateScore} where sql_template_id = #{res.sqlTemplateId}
        </foreach>;
        <!--更新所有字段得分-->
        <foreach collection="list" separator=";" item="res">
            update sql_dimension set field_score = #{res.fieldScore} where dimension_id = #{res.dimensionId}
        </foreach>
</update>

mybatis执行insert语句后,返回当前插入数据主键的方法

blog.csdn.net/NMZLduiduid…

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id" parameterType="com.entity.user">
    insert into test (name) values (#{name})
</insert>
<insert id="saveServerAddress" parameterType="com.xxl.job.admin.core.model.ServerControl">
    <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
        SELECT LAST_INSERT_ID()
    </selectKey>
    INSERT INTO XXL_JOB_SERVER_CONTROL (server) VALUES (#{serverAddress});
</insert>

MyBatis动态SQL、条件查询

有没有办法在SQL语句中将IN与LIKE结合起来?

qa.1r1g.com/sf/ask/4275… 可以使用正则表达式

MySQL数据库插入的几种方式?

解决方案有下面几种:

1、insert into 最普遍的插入,如果表中存在主键相同的数据,执行会报错。
2、replace into 如果表中存在与主键相同的数据,则替换掉该主键的记录,反之则插入(存在就替换,反之插入)
3、insert ignore 如果表中存在主键相同的数据不在插入该条数据,反之则插入(存在则忽略,反之插入)
4、 insert into *** on duplicate key update col1=VALUES(col1),col2=VALUES(col2)...
如果表中存在该记录,则按新的数据进行修改,不存在则插入。(与replace into的区别在于:replace是完全替换成新的数据记录,此处是修改不同的地方,新纪录中没有的部分依然采用老记录中的数据。)

参考链接:
blog.csdn.net/LC_Liangcha…
www.jianshu.com/p/daca7c291…