com.pugwoo.dbhelper.impl.part.P4_InsertOrUpdateOp Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of nimble-orm Show documentation
Show all versions of nimble-orm Show documentation
nimble-orm an ORM based on Spring jdbcTemplate.
package com.pugwoo.dbhelper.impl.part;
import com.pugwoo.dbhelper.utils.DOInfoReader;
import com.pugwoo.dbhelper.utils.InnerCommonUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public abstract class P4_InsertOrUpdateOp extends P3_UpdateOp {
@Override
public int insertOrUpdate(T t) {
if (t == null) {
return 0;
}
if (isWithKey(t)) {
return update(t);
} else {
return insert(t);
}
}
@Override
public int insertOrUpdateWithNull(T t) {
if (t == null) {
return 0;
}
if (isWithKey(t)) {
return updateWithNull(t);
} else {
return insertWithNull(t);
}
}
@Override
public int insertOrUpdate(Collection list) {
if (InnerCommonUtils.isEmpty(list)) {
return 0;
}
// 将insert和update拆开进行调用,更好的利用批量能力
List toInsert = new ArrayList<>();
List toUpdate = new ArrayList<>();
for(T t : list) {
if(t != null) {
if(isWithKey(t)) {
toUpdate.add(t);
} else {
toInsert.add(t);
}
}
}
int rows = 0;
rows += insert(toInsert);
rows += update(toUpdate);
return rows;
}
/**判断对象是否有主键值,必须全部有才返回true*/
private boolean isWithKey(T t) {
List keyFields = DOInfoReader.getKeyColumnsNoThrowsException(t.getClass());
if(keyFields.isEmpty()) {
return false;
}
for(Field keyField : keyFields) {
if(DOInfoReader.getValue(keyField, t) == null) {
return false;
}
}
return true;
}
}