英文:
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 <select>
statements. So you will need to write your statement as a <select>
. 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 <select>
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论