跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • mybatis+pgsql 执行 insert 和 update 之后返回 id
未分類
9 9 月 2020

mybatis+pgsql 执行 insert 和 update 之后返回 id

mybatis+pgsql 执行 insert 和 update 之后返回 id

資深大佬 : jiobanma 3

看到网上是这么写的

<insert id="insertUser">     <selectKey resultType="int"  order="AFTER" keyProperty="pid" >         SELECT currval('tbl_user_pid_seq'::regclass) AS pid     </selectKey>     insert into tbl_user(name, age) values(#{name}, #{age}) </insert> 

tbl_user_pid_seq 是一个序列,但是自己的库 id 没有序列,是自己写了一个 next_id 的函数。 并且因为需要,mybatis 的 parameterType 也不是一个 entity,而是一个 Map 这种时候 xml 该怎么写才能拿到 insert 之后的 id

大佬有話說 (7)

  • 資深大佬 : chihiro2014

    用 JPA 就可以摆脱 XML 地狱了

  • 資深大佬 : ourslay

    试试 spring data jdbc

  • 資深大佬 : yongle1117

    之前遇到过这个问题,我们的解决办法是在 entity 上
    @Id
    @KeySql(genSql = PostgreGenSql.class, order = ORDER.AFTER)
    @Column(insertable = false)
    private Long id;

    public class PostgreGenSql implements GenSql {

    private static final String SQL = “SELECT currval(‘%s_id_seq’::regclass)”;

    @Override
    public String genSql(EntityTable entityTable, EntityColumn entityColumn) {
    return String.format(SQL, entityTable.getName().toUpperCase());
    }

    }

  • 資深大佬 : Takamine

    ……可以试试一个黑魔法,把<insert>标签改成<select>标签使用 pg 的 returning 来做。

  • 主 資深大佬 : jiobanma

    @Takamine #4 我在网上也找到这个黑魔法了,现在用的就是这个,但是不知道会不会有什么其他隐患,但是这样做确实能满足我的需求

  • 資深大佬 : Takamine

    @jiobanma 我觉得应该没有问题(因为我也这么干过 2333 ),本质上 mybatis 拦截应该还是看的执行 sql,标签这个只是目前 mybatis 不支持语法的问题。

  • 主 資深大佬 : jiobanma

    @Takamine #6 哈哈哈 反正也没有找到其他好的方法 先这么凑合着用吧

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具