1

I have little problem. When I try insert new value to database, function save() inserts me different values ​​than are at object :(. What should I do?

Here is my function

public void updateListOfElements(List<Dokumenty> list) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            for (Dokumenty dokument : list) {
                Dokumenty dokumentToUpdate =
                        (Dokumenty) session.get(Dokumenty.class, dokument.getId());

                dokumentToUpdate.setAktywny('N');
                session.update(dokumentToUpdate);    

                // id z dupy wpisuje
                dokument.setId(10114);
                session.save(dokument);
            }

            transaction.commit();
        } catch (HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
        } finally {
            session.close();
        }
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
Mariola
  • 249
  • 7
  • 16

2 Answers2

2

You should use saveOrUpdate not save

 dokument.setId(10114);
 session.saveOrUpdate(dokument);

When you call saveOrUpdate() If the identifier exists, it will call update method else the save method will be called.

If you call save() method stores an object into the database. That means it insert an entry.

Before proceed have a look :What are the differences between the different saving methods in Hibernate?

My suggetion:Always use saveOrUpdate //if record exists update otherwise new

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Use session.merge(). Becuase, NonUniqueObjectException may be thrown when using Session.saveOrUpdate() in Hibernate - See more at: http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/#sthash.WJEbdSaG.dpuf

Masudul
  • 21,823
  • 5
  • 43
  • 58