Last active
September 25, 2015 07:17
-
-
Save paolinux79/6a50b843a6c23009db48 to your computer and use it in GitHub Desktop.
Snippet to update not null value only in JPA/Spring
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
import org.apache.log4j.LogManager; | |
import org.apache.log4j.Logger; | |
import java.lang.reflect.Field; | |
import java.util.Hashtable; | |
/** | |
* Created by paolinux on 9/23/15. | |
*/ | |
/** | |
* Created by paolinux on 9/23/15. | |
*/ | |
public class Updater { | |
private final static Logger log = LogManager.getLogger(Updater.class); | |
public static <E> E updater(E oldEntity, E newEntity) { | |
Field[] newEntityFields = newEntity.getClass().getDeclaredFields(); | |
Hashtable newHT = fieldsToHT(newEntityFields, newEntity); | |
Class oldEntityClass = oldEntity.getClass(); | |
Field[] oldEntityFields = oldEntityClass.getDeclaredFields(); | |
for (Field field : oldEntityFields){ | |
field.setAccessible(true); | |
Object o = newHT.get(field.getName()); | |
if (o != null){ | |
try { | |
Field f = oldEntityClass.getDeclaredField(field.getName()); | |
f.setAccessible(true); | |
log.info("setting " + f.getName()); | |
f.set(oldEntity, o); | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} catch (NoSuchFieldException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
return oldEntity; | |
} | |
private static Hashtable<String, Object> fieldsToHT(Field[] fields, Object obj){ | |
Hashtable<String,Object> hashtable = new Hashtable<>(); | |
for (Field field: fields){ | |
field.setAccessible(true); | |
try { | |
Object retrievedObject = field.get(obj); | |
if (retrievedObject != null){ | |
log.info("scanning " + field.getName()); | |
hashtable.put(field.getName(), field.get(obj)); | |
} | |
} catch (IllegalAccessException e) { | |
e.printStackTrace(); | |
} | |
} | |
return hashtable; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment