From f4d2f06cda36b6ac1cc8cf084e5c58f0032aefa4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=80=E6=BA=90=E6=B5=B7=E5=93=A5?= Date: Mon, 17 Apr 2023 10:08:31 +0800 Subject: [PATCH] add BaseMapper.insertOrUpdate method --- .../java/com/mybatisflex/core/BaseMapper.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/mybatis-flex-core/src/main/java/com/mybatisflex/core/BaseMapper.java b/mybatis-flex-core/src/main/java/com/mybatisflex/core/BaseMapper.java index 9ace1d50..144c7528 100644 --- a/mybatis-flex-core/src/main/java/com/mybatisflex/core/BaseMapper.java +++ b/mybatis-flex-core/src/main/java/com/mybatisflex/core/BaseMapper.java @@ -22,6 +22,8 @@ import com.mybatisflex.core.query.QueryColumn; import com.mybatisflex.core.query.QueryCondition; import com.mybatisflex.core.query.QueryWrapper; import com.mybatisflex.core.query.CPI; +import com.mybatisflex.core.table.TableInfo; +import com.mybatisflex.core.table.TableInfoFactory; import com.mybatisflex.core.util.ObjectUtil; import org.apache.ibatis.annotations.*; import org.apache.ibatis.builder.annotation.ProviderContext; @@ -55,6 +57,23 @@ public interface BaseMapper { @InsertProvider(type = EntitySqlProvider.class, method = FlexConsts.METHOD_INSERT_BATCH) int insertBatch(@Param(FlexConsts.ENTITIES) List entities); + + /** + * 新增 或者 更新,若主键有值,则更新,若没有主键值,则插入 + * + * @param entity 实体类 + * @return 返回影响的行数 + */ + default int insertOrUpdate(T entity) { + TableInfo tableInfo = TableInfoFactory.ofEntityClass(entity.getClass()); + Object[] pkArgs = tableInfo.buildPkSqlArgs(entity); + if (pkArgs.length == 0 || pkArgs[0] == null) { + return insert(entity); + } else { + return update(entity); + } + } + /** * 根据 id 删除数据 * 如果是多个主键的情况下,需要传入数组 new Object[]{100,101}