Last active
November 2, 2017 08:13
-
-
Save wendal/3c13fb8e86f1005f5344 to your computer and use it in GitHub Desktop.
nutz中实现saveOrUpdate封装(供参考)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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