Hibernate - merge() may insert new record

Yes, merge() method is used to update the record for the particular entity but it can create new record for associated entities in some situation.

I have two entity objects user and user-details. User is associated with UserDetial with one-to-one mapping. When I load the user from database using Hibernate session, UserDeatils object also loaded with associated records.When I was making some changes into user details using simple code as shown bellow, it was updating record into user_details table.

Session session=dao.HibernateUtil.getSessionFactory().getCurrentSession();
User u=(User) session.load(User.class,new Long(2));
UserDetails details=u.getUserDetails();
UserDao userDao=new UserDao();


But, when I was using the same code to update the user details with the data getting from user's request ,it was not working as my expectation. It was inserting new record for userdetails into User_deatils table instead of Updating. After long time diagnosis found the solution. Actually, when form was submitting by user, all data was mapping to UserDetail entity bean, but the Id field was missing. So hibernate creating new record for the userdetails without signaling any error. So it have set the id field of Userdeatils with existing Id value of the record to which we want to apply the update operation. So I wrote the following extra line of code.

1 comment:

Anonymous said...

Thanks so much, your post leaded me to right way.

Popular Posts