psisodia
psisodia

Reputation: 1177

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?

Upvotes: 4

Views: 11296

Answers (2)

Raj Kumar
Raj Kumar

Reputation: 1

Make your bean serializable. That will work

Upvotes: -1

Darshan Lila
Darshan Lila

Reputation: 5868

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();

Upvotes: 10

Related Questions