Home How to automatically generate id from 1 with JPA?
Reply: 0

How to automatically generate id from 1 with JPA?

user2339 Published in August 14, 2018, 8:26 am

I am working on rest web services. I found some issue with autogenerated Id with JPA and Spring Boot.
Here are models:

public class Post {    
    @Id @GeneratedValue
    private Long id;

    private String postText;    
    private BlogUser user;    
    private LocalDateTime createdDate;

public class Comment {    
    @Id @GeneratedValue
    private Long id;    
    private String commentText;

Saving objects looks like following:

    Post firstPost = Post.builder()
            .postText("First post !!! UUUUUhuuuuu!")
    Post secondPost = Post.builder()
            .postText("I like this blog posting so much :)")
    Post thirdPost = Post.builder()
            .postText("To be or not to be? What is the question.")


    BlogUser sailor = BlogUser.builder()

    Comment commentToFirstPost = Comment.builder().commentText("you an idiot!")
    Comment secondCommentToFirstPost = Comment.builder().commentText("You should sail to Antarctica!")

However, after it I have instances in DB:

  • Posts:
    1 First post
    2 Second post
    3 Third post

  • Comments:
    4 First comment
    5 Second comment

I want to make comments iteration from 1 because it is completely another class. Not related to posts. It should be like following:

1 First comment
2 Second comment


DB is PostgreSQL. Also, I am interested to know how to do it for MySQL.

How to solve this issue?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.41156 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO