Home > Blockchain >  Spring Boot MongoDB: Can @GeneratedValue and @Column annotations be used?
Spring Boot MongoDB: Can @GeneratedValue and @Column annotations be used?

Time:10-27

I have been learning how to use MongoDB in Spring Boot; for this purpose I am trying to build a service that allows sending posts and commenting on posts in a forum. Currently I have created a model class for forum posts:

@Document
@Data
public class ForumPost {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long postId;

  private Long userId;

  private String postTitle;

  private String postContent;

  @DbRef
  private List<Comment> comments;

  private Instant createTime;

  private Instant updateTime;
  
}

In RDBMS like PostgreSQL I would use @GeneratedValue to automatically generate ID value and @Column to define the column definition and other settings like updatable for each variable. But would this be possible using Spring Data MongoDB? Are there any equivalent annotations that can be used to achieve the same effect?

CodePudding user response:

When we're using MongoDB as the database for a Spring Boot application, we can't use @GeneratedValue annotation in our models as it's not available. Hence we need a method to produce the same effect as we'll have if we're using JPA and an SQL database.

Use this for more reference - click

CodePudding user response:

The id type can be a String or ObjectId(from Mongo drivers), annotated with an @Id(from Spring data commons), Spring Data MongoDB will fill this field automatically when persisting this document.

Check my simple Spring Mongo example and the real world like example.

Generally, the @GeneratedValue is from JPA, only used for JPA entities. If you want to JPA similar APIs on noSQL, check Hibernate OGM.

  • Related