Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

How to use dynamic schema in spring data with mongodb?

Mongodb is a no-schema document database, but in spring data, it's necessary to define entity class and repository class, like following:

Entity class:

@Document(collection = "users")
public class User implements UserDetails {
    @Id private String userId;
    @NotNull @Indexed(unique = true) private String username;
    @NotNull private String password;
    @NotNull private String name;
    @NotNull private String email;
}

Repository class:

public interface UserRepository extends MongoRepository<User, String> {
    User findByUsername(String username);
}

Is there anyway to use map not class in spring data mongodb so that the server can accept any dynamic JSON data then store it in BSON without any pre-class define?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, a few insightful links about schemaless data:

Second... one may wonder if Spring, or Java, is the right solution for your problem - why not a more dynamic tool, such a Ruby, Python or the Mongoshell?

That being said, let's focus on the technical issue.

If your goal is only to store random data, you could basically just define your own controller and use the MongoDB Java Driver directly.

If you really insist on having no predefined schema for your domain object class, use this:

@Document(collection = "users")
public class User implements UserDetails {
    @Id
    private String id;
    private Map<String, Object> schemalessData;

    // getters/setters omitted
}

Basically it gives you a container in which you can put whatever you want, but watch out for serialization/deserialization issues (this may become tricky if you had ObjectIds and DBRefs in your nested document). Also, updating data may become nasty if you're data hierarchy becomes too complex.

Still, at some point, you'll realize your data indeed has a schema that can be pinpointed and put into well-defined POJOs.

Update

A late update since people still happen to read this post in 2020: the Jackson annotations JsonAnyGetter and JsonAnySetter let you hide the root of the schemaless-data container so your unknown fields can be sent as top-level fields in your payload. They will still be stored nested in your MongoDB document, but will appear as top-level fields when the ressource is requested through Spring.

@Document(collection = "users")
public class User implements UserDetails {
    @Id
    private String id;

    // add all other expected fields (getters/setters omitted)
    private String foo;
    private String bar;

    // a container for all unexpected fields
    private Map<String, Object> schemalessData;

    @JsonAnySetter
    public void add(String key, Object value) {
        if (null == schemalessData) {
            schemalessData = new HashMap<>();
        }
        schemalessData.put(key, value);
    }

    @JsonAnyGetter
    public Map<String, Object> get() {
        return schemalessData;
    }

    // getters/setters omitted
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...