0

I have an application which works on Spring MVC and Hibernate . It works fine if a single user insert a record, but if multiple user insert records concurrently at same time . It shows this error "Hibernate: org.hibernate.AssertionFailure: null id in".I can observe this is happening because the automatic primary id genaration by hibernate for all record can be similar because of same time. not sure about this.Please help. Need a crucial fix.

The code I use as follow

@Transactional
public Account addAccount(Account acct) {

      session = sessionFactory.getCurrentSession();
      session.save(acct);
      session.flush();
      session.clear();
      return acct;

}

1 Answers1

0

If you are having concurrency problems consider create this class:

public AccountConcurrencyUtils {

    public static synchronized Account addAccount(Account acct, SessionType session) {
        session = sessionFactory.getCurrentSession();
        session.save(acct);
        session.flush();
        session.clear();
        return acct;
    }

}

Finally in your code:

@Transactional
public Account addAccount(Account acct) {
    return AccountConcurrencyUtils.addAccount(acct, session);
}

This should provent concurrency problems, there should be betters workarounds if you are using Java 7 but this should fix your problem if it is about concurrency, if not, the problem may be other.

I updated the code, put the Session type you are using, this should work even for older Java versions like java 5

Daniel Hernández
  • 4,078
  • 6
  • 27
  • 38