问题
i want update to databgase one of properties for UserData which have(name,street,city,etc) so:
Relationship & DB properties: This UserData have a bi-directional relationship with his User where cascade="save-update" on User.hbm.xml is used, so
User have this properties in DB (id_user, Foreign key: id_UserDetail, status)
UserData have (id_UserDetail,Foreign key: id_User, and classic info fields name,street,telephone,etc )
I use this method to update to database: Update method
public void ajaxNameListener(AjaxBehaviorEvent event) {
UserData usrData = new UserData();
userData.setName(name); // I want update only name property,but unfortunately rest is also overwriten to null in DB
User user = BeanFactory
.getHotelDAOService(User.class)
.findbyIdIndetifier(selectedUserId); // selectedUserId is just identifier from my list of user,so here i declared which concrete User be updated by Id of Users
user.setUserData(userData);
BeanFactory.getHotelDAOService(User.class)
.update(user);
}
This method is used as listener form <a4j:>
on my Jsf page but there is no problem with this,
I need repair this method somehow to update only this DB field what i need and rest must be unchaged, but in this case i succesfully made change for example on field 'name' this update field name by particulary Id, but rest of UserData columns is overwriten to NULL,
Can somebody type me some advice how can be modify this method? or may write own method based on this case, which cause updating only this field what i want update,not rest to NULL in database, Thank a lot for yours post and response, Cheers,
回答1:
This problem occurs because at the time you save/update User's instance, it doesn't have values to its FK properties. So FK properties' values become null.
To avoid this, you can follow either way mentioned below:
- Instead of updating the instance using hibernate API, write an HQL to modify only the property you want to change. (e.g. name in your case.)
- Load the instance of User from hibernate session, change value of the desired property in that instance, Update the User instance. All these 3 operations must be done in a single hibernate session.
来源:https://stackoverflow.com/questions/15250751/how-update-one-specific-property-to-database-without-overwrite-to-null-the-rest