Rahul
Rahul

Reputation: 61

Do select and update as a single query using java hibernate criteria API

I have written an application which read 1 record at a time from a table in Oracle Db, do some processing on it and then save it again to same table. I am also maintaining a status column in the table to keep track of my current record progress.For Eg. initially record status is 'N' after selecting I am updating it to 'U' and at the end change it to 'P'.

Now my problem is I want to run many instance of this application but blocker is same row might be selected by different instance because selecting and updating status to 'U' is not a single query.So it might happen Process 1 select then Process2 select same record then Process1 update status to 'U'.I have to solve this problem to make my application distributed.

I have created select and update query as a single transaction but I guess because that won't solve the problem .My this logic is correct right?

I am using Hibernate to access database .Any one has idea how can I achieve this using Hibernate java?

If my above logic(about transaction) is correct then I can do this by 2 ways if any of these is offered by hibernate.

1-Select and update the record in 1 query

2-Select a row and lock it in 1 query and then run another query in same transaction to update status to 'U' . In Sql I can do this by using 'for update' at end of query but I am not sure how to do this using 'Hibernate criteria'.Criteria also has an API 'forUpdate' but I guess that is not functional because query generated by Hibernate in that case doesn't have 'for update' in last.

Can someone please help me in this

Upvotes: 2

Views: 2724

Answers (1)

Gautam Viradiya
Gautam Viradiya

Reputation: 513

Yes, it is possible to one query using criteria.

I am writing one example. I hope it is helpful to you.

public void updateEmployee(int empid,String firstname, String lastname, String email)
{
    sf=connect(); // get connection
    Session session=sf.openSession();
    Transaction t=session.beginTransaction();

    Employee emp= (Employee) session.get(Employee.class, empid);
    emp.setFirstname(firstname);
    emp.setLastname(lastname);
    emp.setEmail(email);

    session.update(emp);  // Update employee
    t.commit();
    session.close();
}

Upvotes: 1

Related Questions