简体   繁体   中英

Hibernate session updation issue

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?

You can use session.evict(entity) to detach the entity from the session you have loaded it from and then you should be able to update it on the master.

The problem with this approach is that you can't really make transactions, You can't be sure that the entity has not changed in the meanwhile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM