How to automatically generate id from 1 with JPA?

I am working on other web services. I found some problems with automatically generated Idwith JPA and Spring Boot.
Here are the 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 is as follows:

    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 that I have instances in the database:

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

  • Comments:
    4 First comment
    5 Second comment

I want to make comments iterate off 1because this is a completely different class. Not related to messages. It should look like the following:

1 first comment
2 second comment

UPDATE:

PostgreSQL. , MySQL.

?

+4
3

vanilla @GeneratedValue, javax.persistence.GenerationType.AUTO, :

, .

GenerationType.SEQUENCE.

, / , .

, , .

:

@GeneratedValue(strategy = GenerationType.IDENTITY)
+2

- :

public class Post 
{
    @Id
    @SequenceGenerator(name="seq",sequenceName="my_seq")        
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")               
    private Integer id;
}

.

+2

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; 
+1

Source: https://habr.com/ru/post/1692103/


All Articles