7

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?

user2722238
  • 241
  • 1
  • 4
  • 7

5 Answers5

4

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.

Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
1

As of commit 069ceea spring-data-couchbase seems to include support for autogenerating keys using generated keys by properties or unique UUIDs. See HERE for documentation on how to use it.

Mico
  • 1,978
  • 2
  • 13
  • 17
  • I couldn't get this working. Posted the question here: https://stackoverflow.com/questions/47998493/how-are-ids-autogenerated-in-spring-data-couchbase Please help. – User1230321 Dec 28 '17 at 01:59
1

Here is the correct answer.

@Document
public class User {
     @Id @GeneratedValue(strategy = UNIQUE)
     private String id;
     ...
}

as per this link

Ronny Shibley
  • 2,030
  • 22
  • 25
0

In addition, there's a UUID Generator available with Couchbase Java SDK that can help you.

There's a discussion about UUID here.

Community
  • 1
  • 1
  • 1
    yes, using Couchbase's atomic counter documents can serve the purpose of generating a sequence for IDs. Unless using the same counter in every type of document, you'll still need to eg. use a prefix to ensure uniqueness of the id. – Simon Baslé May 02 '16 at 15:25
0

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();
   }

}
Pavan
  • 1,219
  • 13
  • 15