我正在研究休息网络服务。我发现了使用JPA和Spring Boot自动生成Id
的问题
这是模特:
@Entity
public class Post {
@Id @GeneratedValue
private Long id;
private String postText;
@ManyToOne
private BlogUser user;
private LocalDateTime createdDate;
}
@Entity
public class Comment {
@Id @GeneratedValue
private Long id;
private String commentText;
保存对象如下所示:
Post firstPost = Post.builder()
.postText("First post !!! UUUUUhuuuuu!")
.user(carlos)
.createdDate(LocalDateTime.now())
.build();
Post secondPost = Post.builder()
.postText("I like this blog posting so much :)")
.user(carlos)
.createdDate(LocalDateTime.now())
.build();
Post thirdPost = Post.builder()
.postText("To be or not to be? What is the question.")
.user(carlos)
.createdDate(LocalDateTime.now())
.build();
postService.addPost(firstPost);
postService.addPost(secondPost);
postService.addPost(thirdPost);
BlogUser sailor = BlogUser.builder()
.userName("sailor").password("123").email("sailor@gmail.com").build();
userService.addUser(sailor);
Comment commentToFirstPost = Comment.builder().commentText("you an idiot!")
.user(sailor).post(firstPost).createdDate(LocalDateTime.now()).build();
Comment secondCommentToFirstPost = Comment.builder().commentText("You should sail to Antarctica!")
.user(sailor).post(firstPost).createdDate(LocalDateTime.now()).build();
然而,之后我在DB中有实例:
文章:
1第一篇文章
2个帖子
3第三篇文章
评论:
4第一评论
5第二条评论
我想从1
进行注释迭代,因为它完全是另一个类。与帖子无关。它应该如下:
1首先评论
2第二条评论
更新
DB是PostgreSQL。另外,我很想知道如何为MySQL做这件事。
如何解决此问题?
答案 0 :(得分:2)
做这样的事情:
public class Post
{
@Id
@SequenceGenerator(name="seq",sequenceName="my_seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
private Integer id;
}
为每个实体使用不同的序列。
答案 1 :(得分:2)
当您使用香草@GeneratedValue
时,其设置为javax.persistence.GenerationType.AUTO
,其中:
表示持久性提供程序应该选择适当的 特定数据库的战略。
在大多数情况下,实际上是GenerationType.SEQUENCE
。
在这种情况下,hibernate会将其内部序列用于像你这样的普通/香草风格注释的字段。
这可以解释为每个实体不重启计数器,因为那里使用了相同的序列。
您可以尝试强制生成本机ID:
@GeneratedValue(strategy = GenerationType.IDENTITY)
答案 2 :(得分:1)
使用initialValue
TableGenerator
属性
@Id
@TableGenerator(name = "COMMENT_GEN",
table = "id_gen",
pkColumnName = "seq_name",
valueColumnName = "seq_number",
initialValue = 1)
@GeneratedValue(strategy = GenerationType.TABLE, generator = "COMMENT_GEN")
private Long id;