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

How to automatically generate id from 1 with JPA?

user2339
1#
user2339 Published in April 26, 2018, 7:55 am

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

@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;

Saving objects looks like following:

    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();

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

UPDATE:

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.495256 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO