How to use dynamic schema in spring data with mong

2019-01-09 11:14发布

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?

1条回答
狗以群分
2楼-- · 2019-01-09 12:00

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, you can use something like:

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

    // getters/setters omitted
}

data could also ne defined as Map, com.mongodb.DBObject, com.mongodb.BasicDBObject or com.mongodb.BasicDBList.

Basically it gives you a field 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.

查看更多
登录 后发表回答