简体   繁体   English

将 mongo 实体保存到不同的集合

[英]save mongo entity to the different collections

I've been using Spring Data for saving entities to the mongo DB and my code at the moment looks like this:我一直在使用 Spring Data 将实体保存到 mongo DB,目前我的代码如下所示:

I have a repo class:我有一个回购类:

public interface LogRepo extends MongoRepository<Log, String> {

}

and I have an Entity Log which looks like this:我有一个实体日志,如下所示:

@Document(
        collection = "logs"
)
public class Log {

    @Id
    private String id;
    private String jsonMessage;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getJsonMessage() {
        return jsonMessage;
    }

    public void setJsonMessage(String jsonMessage) {
        this.jsonMessage = jsonMessage;
    }
}

and this work well for me, however this approach works only for the case if I want to save Log entities to "logs" collection.这对我来说效果很好,但是这种方法仅适用于我想将日志实体保存到“日志”集合的情况。 However it would be very nice for me to be able to save Log entity to different collections depending on the context.但是,能够根据上下文将 Log 实体保存到不同的集合对我来说非常好。 I mean it would be nice to define collection name in the runtime.我的意思是在运行时定义集合名称会很好。 Is it possible somehow?有可能吗?

Thanks, cheers谢谢,加油

Try to use inheritance and define appropriate collection names in such way.尝试使用继承并以这种方式定义适当的集合名称。 May give you possibility to save in different collections but you will be still not able to specify dynamically collection names and resp.可能让您有可能保存在不同的集合中,但您仍然无法动态指定集合名称和响应。 their amount at runtime.它们在运行时的数量。

@Document(
        collection = "logs"
)
public class Log {

    @Id
    private String id;
    private String jsonMessage;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getJsonMessage() {
        return jsonMessage;
    }

    public void setJsonMessage(String jsonMessage) {
        this.jsonMessage = jsonMessage;
    }
}

@Document(
        collection = "log_child"
)
public class LogChild extends Log{}

With the MongoOperations save method you can choose which class to use and based on the class it will choose the appropriate collection.使用 MongoOperations 保存方法,您可以选择要使用的类,并根据类选择适当的集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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