Ankuj
Ankuj

Reputation: 723

Concurrency Access in Hibernate

I have following code to access the database

        Session session = sessionFactory.openSession();

        String hql ="Select o.id FROM Orders o ORDER BY o.id DESC";
        Query query = session.createQuery(hql);
        query.setFirstResult(0);
        query.setMaxResults(1);

perform some computation from the extracted data and the data produced from calculation should be unique

        session.save(inOrder);
        session.flush();

        session.clear();
        session.close();

But when I run this code when two requests come simultaneously, they get same data and ConstraintViolationException is thrown.

What is the best way to solve this problem

Upvotes: 0

Views: 156

Answers (1)

Denis Borovikov
Denis Borovikov

Reputation: 747

You can lock object being processed using setLockMode, see docs

Upvotes: 1

Related Questions