Link to home
Start Free TrialLog in
Avatar of lam0620
lam0620

asked on

Error duplicate key

I have method insert(UserData[] ud)(Servlet) to insert array UserData into DB(Postgres 7.1) when user click Submit button (JSP)
My problems are when more than a user click Submit button simultaneously, Error duplicate key throw.

Before inserting call method ret = getMaxValues() that return max value of primary key from DB and plus 1.
Primary key in each SQL statement has value is ret ++.

Anyone has experienced my problems, please help.

Thank in advance.

JV.
Avatar of sompol_kiatkamolchai
sompol_kiatkamolchai
Flag of Thailand image

I think you should do insert operation in one atomic command like this.

insert into SOME_TABLE(key, field1, field2, ...) values ((select max(key)+1 from SOME_TABLE), some_value1, some_value2, ...);
Another way is to lock the table when you get next key and release locking table after you insert record but this way may need you to understand more database you use. This is called "ISOLATION LEVEL". you may read this topic more in google.
Avatar of lam0620
lam0620

ASKER

I dont know can  synchronize on method insert(UserData[] ud)?
(
public void synchronize insert(UserData[] ud)?) {
....
}
)

JV.
Yes. You can synchronize in method level too. It's an option you can do buy you should keep in mind that there is no other methods do SQL to the same table.
Avatar of lam0620

ASKER

Hi sompol_kiatkamolchai,

Can you give me a example about using ISOLATION LEVEL?

JV.
ASKER CERTIFIED SOLUTION
Avatar of sompol_kiatkamolchai
sompol_kiatkamolchai
Flag of Thailand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Transaction Isolation Level concept also implement in persistent mechanism like EJB. In EJB we can set what level of isolation we will use. If we set it to highest(Serialize), it will lock that table and release it after completing operation on that table.
It's quite an advance topic for s/b who want to manage transaction on database. If you want to adhoc solve the problem, I recommend you to do insert into table in one atomic operation.
Best luck, :)
the isolation level is not the problem here and is also not a concept to implement serialisition.
Weather you look the complete datebase nor trasaction acrobatics will prevent you from duplicate keys.
You need to prevent the duplicate submission !ee:http://javaalmanac.com/egs/javax.servlet.jsp/myformts.jsp.html?l=new
Uups ..i answerd the wrong thread ..sorry