Spring Data MongoDB: How ignore unique indexed field when Document is embedded in another one?

﹥>﹥吖頭↗ 提交于 2019-12-21 11:03:12

问题


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.



来源:https://stackoverflow.com/questions/36867710/spring-data-mongodb-how-ignore-unique-indexed-field-when-document-is-embedded-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!