Spring Data MongoDB - Annotations



Spring Data MongoDB uses various annotations, lets discuss them in details

Indexes related Annotations

This type of annotation talks about indexing the fields

  • @Indexed

    We have used this annotation above in our Customer document,

  • @CompoundIndexes

    Spring Data MongoDB also supports compound indexes. It s used at Documents level to hold references to multiple fields using single index.

@Document
@CompoundIndexes({ @CompoundIndex(name = "name_salary", def = "{'name.id':1
, 'salary':1}") })
public class Customer {
}

In the above code we have created the compound index with name and salary fields.

Common Annotations

  • @Transient

    As we can guess, The fields which are annotated as @Transient are not part of persistence and they are excluded from being pushed into the database. For instance

public class Customer {
   @Transient
   private String gender;
}

The gender will not be persisted into the database.

  • @Field

    It is used to give a name to the field in the JSON document, We can treat this as the name attribute of @Column annotation of JPA. If we want a JSON document field to be saved other than our java field name, then we use this annotation, For Instance.

@Field("dob")
private Date dateOfBirth;

Here, our Java attribute is dateOfBirth but in the database it will be dob.

Advertisements