如何在PostgreSQL和MyBatis中更新和递增计数器。

huangapple 未分类评论48阅读模式
英文:

How to update and increment a counter in postgresql and mybatis

问题

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.Article">

    <update id="updateClickCount" flushCache="true">
        UPDATE "article"
        SET "click_count" = "click_count" + 1
        WHERE "id" = #{id,jdbcType=NUMERIC}
        RETURNING "click_count" AS update_count;
    </update>

</mapper>
Caused by: org.apache.ibatis.builder.BuilderException: 创建文档实例时出错原因: org.xml.sax.SAXParseException行号: 6列号: 81必须为元素类型update声明属性resultType”。

如何在PostgreSQL和MyBatis中读取更新计数值?

英文:

I am using spring-mybatis and I am doing this update.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.Article">

    <update resultType="java.lang.Long"  id="updateClickCount" flushCache="true">
        UPDATE "article"
        SET "click_count" = "click_count" + 1
        WHERE "id" = #{id,jdbcType=NUMERIC}
        RETURNING "click_count";
    </update>

</mapper>

I expect to be able to read the count in the same request as the one that increment the count.

Instead, it gives me this error:

Caused by: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 81; Attribute "resultType" must be declared for element type "update".

How can I read the update count value in postgrsql and mybatis?

答案1

得分: 0

我相信一个UPDATE...RETURNING语句会在ResultSet中返回值。MyBatis只会解码<select>语句中的ResultSet。所以你需要将你的语句写成一个<select>。这看起来可能很奇怪,但完全可以正常工作。不同的XML标签不会检查包含的SQL是否实际匹配该标签。

另一件需要考虑的事情是,<select>语句在MyBatis中不会自动提交 - 所以根据你如何设置事务管理器,执行语句后你可能需要手动提交。

英文:

I believe that an UPDATE...RETURNING statement returns values in a ResultSet. MyBatis only decodes ResultSets in &lt;select&gt; statements. So you will need to write your statement as a &lt;select&gt;. This will look weird, but will work perfectly fine. The different XML tags don't do any checking to ensure that the included SQL actually matches the tag.

One other thing you will need to think about is that &lt;select&gt; statements do not get committed automatically by MyBatis - so you might need to manually commit after the statement executes depending on how you have setup your transaction manager.

huangapple
  • 本文由 发表于 2020年5月29日 05:36:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/62074954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定