Skip to content
Advertisement

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

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?

Advertisement

Answer

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 use JPA similar APIs on noSQL, check Hibernate OGM.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement