How update one specific property to database,without overwrite to NULL the rest properties

送分小仙女□ 提交于 2019-12-12 05:39:30

问题


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:

  1. 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.)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!