Skip to content

Commit

Permalink
GenId支持批量插入,修改设置id逻辑,如果已经有值,则不生成新的ID覆盖,closed #mybatis-mapper/mapper#94
Browse files Browse the repository at this point in the history
  • Loading branch information
abel533 committed Dec 15, 2023
1 parent 436ebd4 commit 928e266
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
35 changes: 28 additions & 7 deletions src/main/java/io/mybatis/provider/keysql/GenIdKeyGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@
import org.apache.ibatis.session.Configuration;

import java.sql.Statement;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
Expand Down Expand Up @@ -76,9 +80,30 @@ public void processAfter(Executor executor, MappedStatement ms, Statement stmt,
}
}

@SuppressWarnings({"rawtypes", "unchecked"})
public void genId(Object parameter) {
Object id = genId.genId(table, column);
configuration.newMetaObject(parameter).setValue(column.property(), id);
if (parameter != null) {
if (table.entityClass().isInstance(parameter)) {
MetaObject metaObject = configuration.newMetaObject(parameter);
if (metaObject.getValue(column.property()) == null) {
Object id = genId.genId(table, column);
metaObject.setValue(column.property(), id);
}
} else if (parameter instanceof Map) {
new HashSet<>(((Map<String, Object>) parameter).values()).forEach(this::genId);
} else if (parameter instanceof Iterator) {
Iterator iterator = (Iterator) parameter;
Set<Object> set = new HashSet();
while (iterator.hasNext()) {
set.add(iterator.next());
}
set.forEach(this::genId);
} else if (parameter instanceof Iterable) {
Set<Object> set = new HashSet();
((Iterable) parameter).forEach(set::add);
set.forEach(this::genId);
}
}
}

/**
Expand All @@ -94,11 +119,7 @@ public void prepare(Object parameter) {
if (executeBefore) {
if (count.get() < getConcurrency()) {
count.incrementAndGet();
MetaObject metaObject = configuration.newMetaObject(parameter);
if (metaObject.getValue(column.property()) == null) {
Object id = genId.genId(table, column);
metaObject.setValue(column.property(), id);
}
genId(parameter);
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/test/java/io/mybatis/provider/test/User123MapperTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,13 @@ public void testInsert() {
u3.setUsername("hello");
Assert.assertEquals(1, userMapper.insertUser3(u3));
Assert.assertNotNull(u3.getId());
u3.setId(null);
Assert.assertEquals(1, userMapper.insertUser3(u3));
Assert.assertNotNull(u3.getId());
u3.setId(null);
Assert.assertEquals(1, userMapper.insertUser3(u3));
Assert.assertNotNull(u3.getId());
u3.setId(null);
Assert.assertEquals(1, userMapper.insertUser3(u3));
Assert.assertNotNull(u3.getId());
}
Expand Down

0 comments on commit 928e266

Please sign in to comment.