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 have googled a lot about this,but there is no the very solution for me.So,I used a not graceful solution to cover it.
public void setAccount(Account a) throws HibernateException {
try {
Account tmp = (Account) session.
get(Account.class, a.getAccountId());
tmp.setEmail(getNotNull(a.getEmail(), tmp.getEmail()));
...
tmp.setVersion(getNotNull(a.getVersion(), tmp.getVersion()));
session.beginTransaction();
session.update(tmp);
session.getTransaction().commit();
} catch (HibernateException e) {
logger.error(e.toString());
throw e;
}
}
public static <T> T getNotNull(T a, T b) {
return b != null && a != null && !a.equals(b) ? a : b;
}
I receive an Object a
which contains a lot of fields.Those field maybe null
,but I don't want to update them into mysql.
I get an tmp Obejct
from db, and change the field by method getNotNull
,then update the Object.
a Chinese description edition
You should first load the object using the primary key from DB and then copy or deserialize the JSON on top of it.
There is no way for hibernate to figure out whether a property with value null has been explicitly set to that value or it was excluded.
If it is an insert then dynamic-insert=true should work.
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<String, Object> 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.