开发者

MySQL table locking for a multi user JSP/Servlets site

开发者 https://www.devze.com 2023-03-22 04:48 出处:网络
Hi I am developing a site with JSP/Servlets running on Tomcat for the front-end and with a MySql db for the backend which is accessed through JDBC.

Hi I am developing a site with JSP/Servlets running on Tomcat for the front-end and with a MySql db for the backend which is accessed through JDBC.

Many users of the site can access and write to the database at the same time ,my question is : Do i need to explicitly take locks before each write/read access to the db in my code? OR Does Tomcat hand开发者_如何转开发le this for me?

Also do you have any suggestions on how best to implement this ? I have written a significant amount of JDBC code already without taking the locks :/


I think you are thinking about transactions when you say "locks". At the lowest level, your database server already ensure that parallel read writes won't corrupt your tables.

But if you want to ensure consistency across tables, you need to employ transactions. Simply put, what transactions provide you is an all-or-nothing guarantee. That is, if you want to insert a Order in one table and related OrderItems in another table, what you need is an assurance that if insertion of OrderItems fails (in step 2), the changes made to Order tables (step 1) will also get rolled back. This way you'll never end up in a situation where an row in Order table have no associated rows in Order items.

This, off-course, is a very simplified representation of what a transaction is. You should read more about it if you are serious about database programming.

In java, you usually do transactions by roughly with following steps:

  1. Set autocommit to false on your jdbc connection
  2. Do several insert and/or updates using the same connection
  3. Call conn.commit() when all the insert/updates that goes together are done
  4. If there is a problem somewhere during step 2, call conn.rollback()
0

精彩评论

暂无评论...
验证码 换一张
取 消