2

My application uses Spring Boot / JPA / MongoDB.

I map my domain classes to MongoDB using

org.springframework.data.mongodb.core.mapping.Document;
org.springframework.data.mongodb.core.index.Indexed;
org.springframework.data.mongodb.core.mapping.DBRef;

All is well except when trying to make a DBRef unique :

@DBRef @Indexed(unique = true)
private User owner;

I have tried different combinations of @DBRef, @Indexed (unique=true) and cannot make the DBRef unique. I can make other field-types unique, such as 'name' in the following example

@Indexed(unique = true)
@Size(min = 2, max = 100)
@Column(length = 100)
private String name;

but cannot find how to make my DBRef field unique.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
mikec
  • 155
  • 1
  • 17
  • Out of interest: how does the index look on the database level (`colleciton.getIndexes()`) – xeraa Jun 11 '15 at 06:56
  • @xeraa - pls see code below. I have replaced the poorly named 'name' field with smeCode. The DBRef owner is the offending variable. I used db.NT_SMES.getIndexes(), owner is not indexed. smeCode and _id are listed as indexes. (Sorry for not posting code - I couldn't get the comment to format properly) – mikec Jun 11 '15 at 12:32

1 Answers1

0

I'm coming from the Morphia side of mapping, but I'd try this:

@CompoundIndexes({
    @CompoundIndex(name = "owner", def = "{'owner.id' : 1}", unique = true)
})
xeraa
  • 10,456
  • 3
  • 33
  • 66
  • Thx @xeraa. A compound index is not what I want here. I want to mark a DBRef variable as unique. – mikec Jun 11 '15 at 14:00
  • Have you tried it out? This should go into the right direction: http://stackoverflow.com/a/15819034/573153 Since you don't want to index the owner but the owner's ID, you need some workaround. Therefore you'll need some kind of class level association, since the one on the attribute doesn't reach it – xeraa Jun 11 '15 at 14:28
  • @xeraaI did try it, and placed 'unique' in different places. Still can't get 'owner' to be unique. I'll check the MongoTemplate documentation as per your link. Many thanks – mikec Jun 12 '15 at 08:28