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

后端 未结 3 1043
说谎
说谎 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,

    0 讨论(0)
  • 2020-12-29 12:33

    A) Retrive the Parent instance from the Session again and replace by hand the updated fields

    this seems to be the most functional version which i used over the past few years.

    B) Store the Child somewhere (httpSession?) and associate it latter.

    I would advise against this, especially if you want to follow the REST paradigm which makes server side state a complete no-no. And you will end up using heap space for detached objects, although the user who initiated the session left for coffee :)

    C) Set the relation between Parent and Child as immutable.

    IMHO this is not a good way either, although it would be fit for a small project with an small persistence model. But even in a small application it might lead to a headache when trying to modify the code.

    0 讨论(0)
  • 2020-12-29 12:43

    You can modify the detached object directly and then reattach the object to the session using the merge method on the session.

    0 讨论(0)
提交回复
热议问题