将uuid(类型UUID)插入mysql报告重复项PRIMARY

时间:2016-01-12 02:19:59

标签: java mysql uuid

在代码中,通过UUID post_uuid = uuidGenerator.generate()生成UUID,然后插入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();
     }

   }

在mysql中,post_uuid的字段为CHAR(36)

enter image description here

当我运行代码时,它报告错误

enter image description here

错误指向第二个插入sql addParameter("category", category).executeUpdate())

2 个答案:

答案 0 :(得分:2)

它表示在表posts_categories中它具有重键PRIMARY的重复条目

不要将post_uuid作为posts_categories的主键 对于集合categories中的每个元素,您使用相同的postUuid运行INSERT语句。

答案 1 :(得分:1)

尝试使用它的String值

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