I am using hibernate in one of my java applications. The database runs on master slave hierarchy. In one of the classes I am trying to update an existing entity by first getting the entire entity from the master db & then updating it and saving it in the master db. But since this call can increase the load on the master database, I want all the reads to happen from the slave db only, and only updates on the master db. I cannot read from slave & write to master as hibernate somehow saves the session along with the entity and doesn't let you update in some other slavesession.
I came up with a solution:
First I will change the entity to json & then read the json to form a new entity which will hopefully solve the session issue. Below is the code:
private UserEntity getUserEntityForUpdate(UserData userData) {
UserEntity userEntity = (userEntity) sessionFactory.getCurrentSession().byId(userEntity.class).load(user.getId());
ObjectMapper mapper = new ObjectMapper();
String user1 = null;
try {
user1 = mapper.writeValueAsString(userEntity);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
userEntity obj = new UserEntity();
try {
obj = mapper.readValue(user1, userEntity.class);
} catch (IOException e) {
e.printStackTrace();
}
if (obj.getId() != null) {
userEntity.setId(user.getId());
}
obj.setEnabledBy(user.getEnabledBy() != null ? user.getEnabledBy() : "");
obj.setEnabledAt(user.getEnabledAt());
return obj;
}
Just wanted to know if this is a good approach or can I go for any better approach?