简体   繁体   中英

Change the name of the id field

In java Spring and under MongoDB i am creating the following field (id) of a class:

    @Id 
    public String _id;

in order to create the identifier field with the name _id but i get an indentifier id with the compilation warning: WARN 11916 --- [ main] osdmc.m.BasicMongoPersistentProperty: Customizing field name for id property not allowed! Custom name will not be considered! WARN 11916 --- [ main] osdmc.m.BasicMongoPersistentProperty: Customizing field name for id property not allowed! Custom name will not be considered!

My Question is how to change the name of the id field in java spring (if that's even possible)

EDIT: i tried with @Field("_id") but it's not working.

Thank you,

TL;DR

The warning comes from MongoDB which is unhappy of an @Id field having a property name other than those supported by spring data based on the root cause

Based of the supported Id fields names stored in the Set SUPPORTED_ID_PROPERTY_NAMES includes {"id", "_id}.

That being said your naming of id field should be accepted which is apparently not. It may come from another document. You should check how many @Document you have.

Usually, a basic mongoDB document in Spring includes two main information:

  1. The @Document annotation in the model object (eg a User)
  2. The @Id annotation from the id property in the model class

Here an example:

@Document
public class User {
     
     @Id
     private BigInteger id;

     // other fields
     /**
      * Returns the identifier of the document.
      * 
      * @return the id
     */
    public BigInteger getId() {
         return id;
    }

    // getters & setters for other fields (id have only a getter /!\)
}

What you described in your question description is more convenient for JPA based entity for SQL-databases and not suitable for MongoDB document.

Also, I encourage you to check Spring Data MongoDB project and this sample project to see "best practice to start with" when creating such projects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM