facebook

default value for primary key does not work

  1. MyEclipse IDE
  2.  > 
  3. Off Topic
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #248796 Reply

    SEanLon11
    Member

    I 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

    #248894 Reply

    Riyad Kalla
    Member

    Moving 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.

    #248905 Reply

    Haris Peco
    Member

    Sean,

    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 name

    for 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 generator

    and tell hibernate that use

    Best

Viewing 3 posts - 1 through 3 (of 3 total)
Reply To: default value for primary key does not work

You must be logged in to post in the forum log in