- This topic has 2 replies, 3 voices, and was last updated 19 years, 1 month ago by
Haris Peco.
-
AuthorPosts
-
SEanLon11MemberI am trying to insert some simple values into a table, but when I use ” INSERT INTO phones VALUES(default, ‘2546543453’, ‘cell phone’); ” in my Java code, I get the following error:
Exception in thread “main” org.postgresql.util.PSQLException: ERROR: duplicate key violates unique constraint “pk_phones”
I have also tried to insert with: “INSERT INTO phones(phoneid, phoneno, description) VALUES(default, ‘2546543453’, ‘phone’);” But, when I substitute a valid primary key instead of the keyword default, it works fine.
The schema is:
phones(phoneID SERIAL, phoneno TEXT, description TEXT);
I am also using Hibernate3 to map my objects, and if I simply try to save the Phone object into the database using Hibernate3, it works fine as well. However, I want to perform more complex inserts, updates, and queries simply using JDBC, but am running into the above problem using the keyword “default”. If anyone knows a way to work around this (besides retrieving each tuple, totalling them, and then adding 1), I would appreciate it greatly.
Thanks,
Sean
Riyad KallaMemberMoving to OT > Soft Dev
Sean,
Make your PK field auto-increment, let the DB increment the primary key, there is no reason you need to be doing this, the DB is better at it anyway. Then just do INSERT INTO of the last 2 values and the DB will fill in the key.
Haris PecoMemberSean,
You can’t insert default value in PK (2 rows can’t have same primary key) and this is normal behavior
As Ryiad says, you want auto increment (or sequence or trigger and it depend from database)
You can choose generator when you make mapping, but in future release you will can add sequence namefor your example just choose increment for generator in hibernate mapping and forget about inserting phoneId
in jdbc (or mysql, i suppose that you use mysql) you insert like this
INSERT INTO phones(phoneno, description) VALUES( ‘2546543453’, ‘phone’)
Hibernate will do it automatic when you set correct generatorand tell hibernate that use
Best
-
AuthorPosts