How to tell Spring Data Couchbase to embed or reference entity?

Viewed 492

My question is simple: how do I tell Spring Data Couchbase to either embed or reference an entity using @Field? Is there an extra annotation to it?

2 Answers

Not sure about which extra annotation you're asking for.

According to the documentation:

All entities should be annotated with the @Document annotation.

Also, every field in the entity should be annotated with the @Field annotation from the Couchbase SDK. While this is - strictly speaking - optional, it helps to reduce edge cases and clearly shows the intent and design of the entity. It can also be used to store the field under a different name.

There is also a special @Id annotation which needs to be always in place. Best practice is to also name the property id.

For example:

    import com.couchbase.client.java.repository.annotation.Id;
    import com.couchbase.client.java.repository.annotation.Field;
    import org.springframework.data.couchbase.core.mapping.Document;

    @Document
    public class User {

        @Id
        private String id;

        @Field
        private String firstname;

        @Field
        private String lastname;

        public User(String id, String firstname, String lastname) {
            this.id = id;
            this.firstname = firstname;
            this.lastname = lastname;
        }

        public String getId() {
            return id;
        }

        public String getFirstname() {
            return firstname;
        }

        public String getLastname() {
            return lastname;
        }
    }

Being said this, there is another annotation in the documentation that may be helpful:

If you want a different representation of the field name inside the document in contrast to the field name used in your entity, you can set a different name on the @Field annotation. For example if you want to keep your documents small you can set the firstname field to @Field("fname"). In the JSON document, you’ll see {"fname": ".."} instead of {"firstname": ".."}.

You can't reference other documents using @Field, the goal of this annotation so far is only to specify the name of your attribute in the final JSON document, but the @Field annotation is not mandatory.

Regarding the ID reference validation, there are a lot of side effects on adding such a feature/validation, one of them is that your write throughput will be significantly impacted. MongoDB has a Master/Slave architecture, which enables this feature to be easily implemented, on the other hand, it sacrifices scalability.

Couchbase approach prefers to rely on your application to do such validation (it is the application responsibility to save the correct data anyways) but make your reads/writes as fast as possible.

My Personal View: This kind of validation is just an RDBMS "bureaucracy", as your application already validates everything.

Related