-->

Spring Data MongoDB: How ignore unique indexed fie

2020-07-07 03:36发布

问题:

I have a Contract class defined like this:

@Document
public class Contract {

    @Id
    private String id;

    @Indexed(unique = true)
    private String ref;

    private String status = "pending";

    // getter & setter & hashcode & equals & tostring...
}

I want to save contract state over time, so I created a Version class like this:

@Document
public class Version {

    @Id
    private String id;

    private Contract contract;

    private Instant createdAt;

    // getter & setter & hashcode & equals & tostring...
}

When I try to save multiple times the version object over time, I have a duplicate keys exception. I think it's the duplicate key index on contract's ref which complains here.

How can I achieve this kind of thing?

回答1:

Simply add @Reference like this:

@Document
public class Version {

  @Id
  private String id;

  @Reference
  private Contract contract;

  private Instant createdAt;

  // getter & setter & hashcode & equals & tostring...
}


回答2:

I am not sure if there is a way to achieve this from spring context.

The best way is to remove all the indices definition outside of your code. i.e apply through an offline script. You can apply scripts using tools like mongeez. It can be configured to run on application startup, so you can ensure its always run irrespective of location.

Once the application is live we might want to build new indices in a controlled manner. Having embedded in the code may not give this advantage as it will run only on startup.

If you are using offline scripts you are in total control.