Is there a setting in hibernate to ignore null values of properties when saving a hibernate object?
NOTE
In my case I am de-serial
I bumped into this problem and I did a work-around to help myself through this. May be a little ugly but may work just fine for you too. Kindly if someone feels there's an adjustment that's good to have feel free to add. Note that the work-around is meant for valid entity classes and whose some fields include nullable attributes. Advantage with this one is it reduces the number of queries.
public String getUpdateJPQL(Object obj, String column, Object value) throws JsonProcessingException, IOException {
//obj -> your entity class object
//column -> field name in the query clause
//value -> value of the field in the query clause
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(obj);
Map map = mapper.readValue(json, Map.class);
Map format = new HashMap();
if (value instanceof String) {
value = "'" + value + "'";
}
map.keySet()
.forEach((str) -> {
Object val = map.get(str);
if (val != null) {
format.put("t.".concat(str), "'" + val + "'");
}
});
String formatStr = format.toString();
formatStr = formatStr.substring(1, formatStr.length() - 1);
return "update " + obj.getClass()
.getSimpleName() + " t set " + formatStr + " where " + column + " = " + value + "";
}
Example: For entity type User
with fields: userId
, userName
& userAge
; the result query of getUpdateJPQL(user, userId, 2)
should be update User t set t.userName = 'value1', t.userAge = 'value2' where t.userId = 2
Note that you can use json annotations like @JsonIgnore
on userId
field to exclude it in deserialization i.e. in the generated query.
You can then run your query using entityManager or hibernate sessions.