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
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
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,
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.
You can modify the detached object directly and then reattach the object to the session using the merge method on the session.