简体   繁体   中英

Hibernate: saveorupdate() not updating the object

I am using spring to maintain the transaction in my application. I want to save new and update the existing userdetails in DB.But I am not able to update my changes to database. See my below code and tell what I am doing wrong in my code?

 Session session = getSessionFactory().getCurrentSession();
            UserDetails userDetails = (UserDetails) session.get(
                    UserDetails.class, new Integer(userId));

            if (userDetails!= null) {           
                userDetails.setUserName(name);
                userDetails.setUserDesc(desc);
            } else {
                userDetails= new UserAuthDetails();
                userDetails.setId(userId);
                userDetails.setUserName(name);
                userDetails.setUserDesc(desc);
                userDetails.setCreatedDt(new Date());
            }

            session.saveOrUpdate(userDetails);

Can anyone help to update the existing userdetail object?

You need to begin a transaction before saving or updating to the database. Your Code should look as follows:

 Session session = getSessionFactory().getCurrentSession();
 Transaction tx=session.beginTransaction();
        UserDetails userDetails = (UserDetails) session.get(
                UserDetails.class, new Integer(userId));

        if (userDetails!= null) {           
            userDetails.setUserName(name);
            userDetails.setUserDesc(desc);
        } else {
            userDetails= new UserAuthDetails();
            userDetails.setId(userId);
            userDetails.setUserName(name);
            userDetails.setUserDesc(desc);
            userDetails.setCreatedDt(new Date());
        }

        session.saveOrUpdate(userDetails);
        tx.commit();

Make your bean serializable. That will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM