Skip to content

Instantly share code, notes, and snippets.

@wendal
Last active November 2, 2017 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wendal/3c13fb8e86f1005f5344 to your computer and use it in GitHub Desktop.
Save wendal/3c13fb8e86f1005f5344 to your computer and use it in GitHub Desktop.
nutz中实现saveOrUpdate封装(供参考)
@SuppressWarnings("unchecked")
public static <T> T insertOrUpdate(Dao dao, T obj) {
if (obj == null)
return null;
Entity<T> en = (Entity<T>) dao.getEntity(obj.getClass());
if (en.getPkType() == PkType.UNKNOWN)
throw new IllegalArgumentException("no support , without pks");
boolean doInsert = false;
switch (en.getPkType()) {
case ID:
Number n = (Number) en.getIdField().getValue(obj);
if (n == null || n.intValue() == 0)
doInsert = true;
break;
case NAME:
if (null == en.getNameField().getValue(obj))
doInsert = false;
break;
case COMPOSITE:
doInsert = true;
for(MappingField mf :en.getCompositePKFields()) {
Object v = mf.getValue(obj);
if (v != null) {
if (v instanceof Number && ((Number)v).intValue() != 0) {
continue;
}
doInsert = true;
}
}
case UNKNOWN:
throw Lang.impossible();
}
if (doInsert) {
return dao.insert(obj);
} else{
dao.update(obj);
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment