我正在研究休息网络服务。我发现使用 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();
但是,在它之后我在数据库中有实例:
帖子:
1 第一篇文章
2 第二篇文章
3 第三篇评论:
4 第一条评论
5 第二条评论
我想从 1
进行评论迭代,因为它完全是另一个类。与帖子无关。它应该像下面这样:
1条评论
2 第二条评论
更新:
数据库是 PostgreSQL。另外,我很想知道如何为 MySQL 做到这一点。
如何解决这个问题?
最佳答案
当你使用普通的 @GeneratedValue
时,它的设置有一个 javax.persistence.GenerationType.AUTO
,它:
Indicates that the persistence provider should pick an appropriate strategy for the particular database.
在大多数情况下,这实际上是 GenerationType.SEQUENCE
。
在那种情况下,hibernate 将使用它的内部序列来注释字段,就像你的一样。
这可以解释计数器不会为每个实体重新启动,因为那里使用相同的序列。
不过您可以尝试强制生成 native ID:
@GeneratedValue(strategy = GenerationType.IDENTITY)
关于java - 如何使用 JPA 从 1 自动生成 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48229499/