Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle the transaction in J2EE 1.4 with plain JDBC

I am developing a hotel booking site. It is a J2EE 1.4 web application and using JSP and JDBC.

I have one method which is responsible to book the hotel rooms.

booking()

And from this method I am calling other four methods

bookRooms()
makePayment()
confirmUserByMail()
confirmUserBySMS()

I am aware that two users can try to book the same room at the same time and in my current system it is possible that two users might end up with the same room.

How should I handle the transaction to avoid this concurrency issue?

It might be very common scenario but I never handled this kind of scenario before, so please guide me.

like image 223
Bacteria Avatar asked Jun 12 '15 19:06

Bacteria


People also ask

How do we usually perform transaction management in JDBC?

We can use the setAutoCommit, commit and rollback methods to manage transactions using JDBC. We can use PreparedStatement in transactions to execute the SQL statement, after using PreparedStatement in the statement will execute as per transaction order.

How do I commit a transaction in JDBC?

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.

How do I start a transaction in JDBC?

Staring a transaction You can enable manual-transaction support by turning off the auto-commit mode. To do so, you need to passing the boolean value false to the setAutoCommit() method of the Connection interface.

Does JDBC automatically commit a transaction?

By default, JDBC uses an operation mode called auto-commit. This means that every update to the database is immediately made permanent. Any situation where a logical unit of work requires more than one update to the database cannot be done safely in auto-commit mode.


1 Answers

Easiest way is add locks in your code or use locks provided by database.You can use volatile or other concurrent tools in java.

If the amount of user is not too large,you can use message queue.Visit from user is encapsulated into object, put the object into the queue and wait for process by threads. It's gonna cost a lot of memory space if there are too many users.

I've heard another way called Optimistic lock,but I've never used it in practice,you can try.

ps If the amount of user is very large,perhaps you should use cache like Memcached.Manipulate datas in the memory and map these changes to database later

like image 145
Ryan_Wang Avatar answered Oct 01 '22 14:10

Ryan_Wang