在代码中,通过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)
当我运行代码时,它报告错误
错误指向第二个插入sql addParameter("category", category).executeUpdate())
答案 0 :(得分:2)
它表示在表posts_categories中它具有重键PRIMARY的重复条目
不要将post_uuid
作为posts_categories
的主键
对于集合categories
中的每个元素,您使用相同的postUuid
运行INSERT语句。
答案 1 :(得分:1)
尝试使用它的String值
.addParameter("post_uuid", postUuid.toString ())