Last active
December 3, 2015 21:44
-
-
Save rhyek/7bba7da7747996177f7a to your computer and use it in GitHub Desktop.
RushOrm @IdentityColumn annotation
This file contains hidden or 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
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.FIELD) | |
public @interface IdentityColumn {} | |
public class MyRushObject extends RushObject { | |
@RushIgnore | |
public transient boolean _didRegisterObjectId = false; | |
@RushIgnore | |
private transient String _identityValue; | |
private List<Field> getAllFields() { | |
List<Field> fields = new ArrayList<>(); | |
for (Field field : getClass().getDeclaredFields()) { | |
fields.add(field); | |
} | |
for (Field field : getClass().getFields()) { | |
if (!fields.contains(field)) | |
fields.add(field); | |
} | |
return fields; | |
} | |
public String getIdentityValue() { | |
if (identityValue == null) { | |
for (Field field : getAllFields()) { | |
if (field.isAnnotationPresent(IdentityColumn.class)) { | |
field.setAccessible(true); | |
try { | |
identityValue = field.get(this).toString(); | |
} catch (IllegalAccessException ignore) {} | |
break; | |
} | |
} | |
} | |
return identityValue; | |
} | |
private void registerObjectWithIdentityRecursively(List<MyRushObject> done, MyRushObject record) { | |
if (record == null || done.contains(record)) | |
return; | |
if (!record._didRegisterObjectId) { | |
String id = record.getIdentityValue(); | |
if (id != null) { | |
RushCore.getInstance().registerObjectWithId(record, id); | |
record._didRegisterObjectId = true; | |
} | |
} | |
done.add(record); | |
for (Field field : record.getAllFields()) { | |
try { | |
field.setAccessible(true); | |
if (MyRushObject.class.isAssignableFrom(field.getType())) { | |
registerObjectWithIdentityRecursively(done, (MyRushObject) field.get(record)); | |
} else if (field.isAnnotationPresent(RushList.class) && MyRushObject.class.isAssignableFrom(field.getAnnotation(RushList.class).classType())) { | |
List<MyRushObject> children = (List) field.get(record); | |
for (MyRushObject child : children) { | |
registerObjectWithIdentityRecursively(done, child); | |
} | |
} | |
} catch (IllegalAccessException ignore) {} | |
} | |
} | |
public void save() { | |
List<MyRushObject> done = new ArrayList<>(); | |
registerObjectWithIdentityRecursively(done, this); | |
super.save(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment