L. YanJun
L. YanJun

Reputation: 277

When insert uuid (Type UUID) into mysql report duplicate entry for key PRIMARY

In the code, through UUID post_uuid = uuidGenerator.generate() generate a UUID, then insert into the mysql.

   Connection conn = sql2o.beginTransaction();
   UUID postUuid = uuidGenerator.generate();

   conn.createQuery("insert into posts(post_uuid, title, content, publishing_date) values (:post_uuid, :title, :content, :date)")
        .addParameter("post_uuid", postUuid.toString())
        .addParameter("title", title)
        .addParameter("content", content)
        .addParameter("date", new Date())
        .executeUpdate();

   categories.forEach(category -> 
        conn.createQuery("insert into posts_categories(post_uuid, category) VALUES (:post_uuid, :category)")
        .addParameter("post_uuid", postUuid.toString())
        .addParameter("category", category)
        .executeUpdate());

   conn.commit();
   return postUuid;

RandomUuidGenerator Class

     public class RandomUuidGenerator implements UuidGenerator{

     @Override
     public UUID generate() {
        // TODO Auto-generated method stub
        return UUID.randomUUID();
     }

   }

In mysql, the field of post_uuid was CHAR(36)

enter image description here

When I run the code, it report a error

enter image description here

The error points to second insert sql addParameter("category", category).executeUpdate())

Upvotes: 0

Views: 1536

Answers (2)

VolkerK
VolkerK

Reputation: 96159

it said that in table posts_categories it has the duplicate entry for key PRIMARY

Don't make post_uuid the primary key of posts_categories.
For each element in your collection categories you run the INSERT statement with the same postUuid.

Upvotes: 2

Scary Wombat
Scary Wombat

Reputation: 44854

try using the String value of it

 .addParameter("post_uuid", postUuid.toString ())

Upvotes: 1

Related Questions