Linux 拨号vps windows公众号手机端

mybatis中saveorupdate怎么实现

lewis 9年前 (2016-11-13) 阅读数 7 #程序编程
文章标签 mybatis

在 MyBatis 中并没有提供类似 Hibernate 中的 saveOrUpdate 方法,但是可以通过自定义 SQL 语句来实现类似的功能。首先根据实体的唯一标识(如主键)查询数据库,如果存在记录则执行更新操作,如果不存在则执行插入操作。

示例代码如下:

public void saveOrUpdate(Entity entity) {
    Entity existingEntity = sqlSession.selectOne("selectById", entity.getId());

    if (existingEntity != null) {
        sqlSession.update("update", entity);
    } else {
        sqlSession.insert("insert", entity);
    }
}

其中,selectByIdupdateinsert 是自定义的 SQL 语句,需要在对应的 Mapper XML 文件中进行定义。这样就实现了类似于 saveOrUpdate 的功能。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门