Skip to content

How to implement concurrency in hibernate

I am beginner in hibernate, I am developing a web application for local institute which will provide online classes to the students, so for each session there are limited 20 seats, system suppose to be able to register 20 students, I want to handle a use case where at a time 20+ students are registering at a same time, So implementation should be like if 20th student registered then system display the notification, how would I achieve this using hibernate.

The solution which I am thinking is achieved by introducing triggers in Database end, which is not supposed to be good practice at all.

I know that Hibernate is quite advanced enough to handle such things, I want to show the seat counts also on the basis of real time data, so please suggest me the solution and best practices.

Answer

Create an entity CourseSeats and insert a row per seat that can be booked. The booking of a seat would do something like UPDATE CourseSeats s SET s.student = :student WHERE s.id = (SELECT MIN(s2.id) FROM CourseSeats s2 WHERE s2.student IS NULL). When the update count is 0, it means there are no more seats available. To check how many seats are available you could do SELECT COUNT(*) FROM CourseSeats s WHERE s.student IS NULL. Just execute that query every once in a while and if it returns 0, you can notify the user.