Payal Bansal
Payal Bansal

Reputation: 755

save not throwing error even if record with key exist in db

I wrote this code:

            Account ac= new Account();
    ac.setId(1);
    ac.setType("checking");
    ac.setAmount(12344.43);
    //Transient

    Configuration cfg= new Configuration();
    cfg.configure("hibernate.cfg.xml");
    try(Session s=sf.openSession();Session s1=sf.openSession()){
    s.beginTransaction();
    s.save(ac);//dirty checking
    ac.setAmount(3000);
    s.flush();
    s.getTransaction().commit();
    ac.setAmount(5000);
    Account ac1=s1.get(Account.class, 1);
    ac1.setAmount(8000);
    s1.save(ac1);
    s1.beginTransaction().commit();
    }
    sf.close();

In second session when we saving the account object again it should throw an error but it does not. Any pointers regarding this?

Upvotes: 0

Views: 45

Answers (2)

Payal Bansal
Payal Bansal

Reputation: 755

Once we have done ac1.setAmount(8000); the database would be updated with the latest data. But since the account object is already associated to the session with latest data, no save query would be fired to the db hence no error.

To illustrate,

        Account ac= new Account();
    ac.setId(2);
    ac.setType(AccountType.CHECKING);
    ac.setDateOfOpening(LocalDateTime.now());
    ac.setAmount(12344.43);

    Configuration cfg= new Configuration();
    cfg.configure("hibernate.cfg.xml");
    Session s=sf.openSession();
    s.save(ac);
    ac.setType(AccountType.CHECKING);
    s.beginTransaction().commit();
    s.close();
    sf.close();

It does not fire any update query in db, only 1 insert. So if the state is not changing, and it is in persistent state ,it does not perform update/ save

Upvotes: 0

Ishan Thilina Somasiri
Ishan Thilina Somasiri

Reputation: 1244

Since you are saving on the same id,

Account ac1=s1.get(Account.class, 1);

You'll only be updating the existing record (with ID = 1).

If you are interested in learning the behaviour of save and other persisting methods in-depth, a good article is avaialble at http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate .

Upvotes: 1

Related Questions