Best way to update some fields of a detached object on Hibernate?

后端 未结 3 1061
说谎
说谎 2020-12-29 11:50

I was wondering what\'s the best way to update some fields of a dettached object using HB on Java. Specially when the object has child objects attributes. For Example (annot

3条回答
  •  半阙折子戏
    2020-12-29 12:32

    After loading a Parent object, you said

    Now, I only want to allow the user to update the field2 attribute of the parent

    Based on Use case, you can use a UpdateableParent object

    public class UpdateableParent {
    
       private String field2;
    
       // getter's and setter's
    
    }
    

    Now our Parent repository

    @Repository
    public class ParentRepositoryImpl implements ParentRepository {
    
        @Autowired
        private SessionFactory sessionFactory;
    
    
        public void updateSpecificUseCase(UpdateableParent updateableParentObject) {
    
            Parent parent = sessionFactory.getCurrentSession().load(Parent.class, updateableParentObject.getId());
    
            try {
                // jakarta commons takes care of copying Updateable Parent object to Parent object
    
                BeanUtils.copyProperties(parent, updateableParentObject);
            } catch (Exception e) {
                throw new IllegalStateException("Error occured when updating a Parent object", e);
            }
    
        }
    
    }
    

    Its advantages

    • It is safe: you just update what you really want
    • You do not have to worry about MVC framework (Some MVC framework allows you set up a allowedFields property). What happens if you forget some allowed fields ???

    Although it is not a Technology-related question, Seam framework allows you update only what you want. So you do not have to worry about what pattern to use.

    regards,

提交回复
热议问题