javawildfly

How to avoid the inconsistency of data while inserting into table


A is a table

I have created a java web based application and deployed in wildfly server. The column a1 is readonly to the enduser, and it will show the maximum count of the rows in table A and a2 is an editable column.

Now consider two end users are accessing this application at same time and trying to insert data into the table A. Both these users will see the same value for column a1, and give different values in the column a2. Now both the users submit the application and will insert data into A.

This will result in inserting two rows with the same value for the column a1. But a1 is the primary key. So it should have distinct values.

How can I prevent this while inserting data in table A? Here do we need to apply threading concept?


Solution

  • Use ID generator. There are different types possible, e.g. based on database sequence like in Oracle, based on auto increment in MySQL.

    Here are some good examples: