I'm setting up a Document with the @Id annotation and in my tests I get a MappingException because the Id is not set when creating a new document. Is spring-data + couchbase unable to automatically assign an ID for new documents?
5 Answers
There is no auto-generation of IDs in Couchbase, so you need to set one.
Keep in mind that Couchbase can store heterogeneous data in the same Bucket, so by default if you have several types of entities, they'll end up in the same storage unit. Therefore if you have eg. User and Product entities, creating and saving a User which @Id is "foo" then a Product also id-ed "foo" will end up overwriting the User with the Product.
What I mean is, you have to provide the @Id and make sure no ID collide, even across entity classes.
Here is the correct answer.
@Document
public class User {
@Id @GeneratedValue(strategy = UNIQUE)
private String id;
...
}
as per this link
In addition, there's a UUID Generator available with Couchbase Java SDK that can help you.
There's a discussion about UUID here.
You can generate the UUID as unique using Java. This will generate UUID by Java. Can be used as unique in Couchbase PK.
@Document
public class BasicEntity {
@Id
@Field
private String _id;
/**
* @return the _id
*/
public String get_id() {
return _id;
}
/**
*/
public void set_id() {
this._id = UUID.randomUUID().toString();
}
}