Search code examples
javamongodbjava-ee-6morphia

Index violation on a referenced class, Morphia


I am trying to persist a one (Owner) to many (Car) relation with morphia(0.99)/mongoDB(2). When I try to persist class Car with a reference to class Owner, Morphia throws an MongoException$DuplicateKey exception. This is strange since I thought that cascade persisting didn't existed in morphia.

Why is morphia throwing a duplicate key exception for index *index_username* on the referenced class Owner when I persist Car?

Pojo:

@Entity(noClassnameStored=true, value="base")
public class Base {

    @Id
    private ObjectId id;
    ...


@Entity(value = "owner", noClassnameStored = true)
@Polymorphic
public class Owner extends Base {

    @Indexed(value = IndexDirection.ASC, unique=true, dropDups=true, name="index_username")
    private String userName;

    @Reference
    private Set<Car> cars = new HashSet<Car>();
    ... 

@Entity(value="car", noClassnameStored=true)
@Polymorphic
public class Car extends Base{
    @Reference
    private Owner owner

Bean:

car.setOwner(owner);
BeanUtil.getDataStore().save(car);

Exception:

com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: myapp.car.$index_username  dup key: { : null }

Solution

  • You can't add more than one null reference. Either add a value for all entities (up to 1 may be null) or set sparse=true on the index so you can have unique values, but allow multiple null