Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock whole entity (table) in JPA entity manager

I have a table from which I'm calculating the current number of rows between two dates and using the resultant value in my 'to be inserted' rows in that same table.

I'm having issue when two concurrent requests come, say A1 and A2, and want to store new rows at the same time (after the calculation above), both have the same resultant, say 10 rows. Even though A1 should have 10, while A2 should get 11.

Both transactions are conflicting. So I need to lock the table. I know the lock function

aRepository.lock(Object);

but the issue is that this will lock only a row, and I want to lock the whole table(entity) as I'm calculating the total number of rows.

like image 555
ihaider Avatar asked May 27 '14 09:05

ihaider


1 Answers

As far as i know you cannot lock the whole table with JPA. But of course you can use native queries to do that. Why don't you use a sequence like this in you entity:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

You would be able to work parallel instead of running one after the other.

If you really insist on making in one after the other you can also have a little table with one column and one row. There you can use

aRepository.lock(Object);

But I would not advise this.

like image 100
Hasan Tuncay Avatar answered Oct 14 '22 03:10

Hasan Tuncay