小编典典

我们如何使用Spring Boot为MongoDB创建自动生成的字段

spring-boot

我写了一些代码,我想在BaseQuestionClass中将QuestionId 字段设置为Autogenic,对此有什么解决方案?我没有使用jpa
jar.so我不能使用@Generatedvalue注释。所以我们在这里显示的是自动生成的。代码如下。

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>audit_project</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

BaseQuestion.java

package model;

import java.util.List;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "basequestion")
public class BaseQuestion {
      @ID
    private String id;
    private int questionId;
    private String responseType;
    private boolean required;
    private boolean active;
    private String questionCode;
    private QuestionText questionText;
    private String category;
    private List<Responses> responses;

    public QuestionText getQuestionText() {
        return questionText;
    }

    public void setQuestionText(QuestionText questionText) {
        this.questionText = questionText;
    }

    public List<Responses> getResponses() {
        return responses;
    }

    public void setResponses(List<Responses> responses) {
        this.responses = responses;
    }

    public int getQuestionId() {
        return questionId;
    }

    public void setQuestionId(int questionId) {
        this.questionId = questionId;
    }

    public String getResponseType() {
        return responseType;
    }

    public void setResponseType(String responseType) {
        this.responseType = responseType;
    }

    public boolean getRequired() {
        return required;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    public String getQuestionCode() {
        return questionCode;
    }

    public void setQuestionCode(String questionCode) {
        this.questionCode = questionCode;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }
}

AuditProjectRepository.java

package repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import model.BaseQuestion;

public interface AuditProjectRepository extends MongoRepository<BaseQuestion, String> {

    public BaseQuestion findByQuestionId(int questionId);

    public BaseQuestion findByQuestionCode(String questionCode);

    public Long deleteByQuestionId(int questionid);

}

阅读 404

收藏
2020-05-30

共1个答案

小编典典

MongoDB具备所有复杂的ObjectId生成功能,但是通常您只是从关系数据库中跳了出来,而且您仍然想要一个易于读取/交流的数字标识符字段,该字段在每次插入新记录时都会自动递增。

MongoDB教程中的一项巧妙建议是使用一个计数器集合,该计数器集合以“ counter name”作为其ID,并使用“
seq”字段存储最后使用的数字。

当使用Spring Data MongoDB开发时,这个巧妙的技巧可以写成一个简单的服务。在这里,我使用集合名称作为计数器名称,因此很容易猜测/记住。

import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.model.CustomSequences;


@Service
public class NextSequenceService {
    @Autowired private MongoOperations mongo;

    public int getNextSequence(String seqName)
    {
        CustomSequences counter = mongo.findAndModify(
            query(where("_id").is(seqName)),
            new Update().inc("seq",1),
            options().returnNew(true).upsert(true),
            CustomSequences.class);
        return counter.getSeq();
    }
}

CustomSequences只是表示集合的简单类。请注意int数据类型的使用,这将限制为2 ^ 31个条目的最大值。

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "customSequences")
public class CustomSequences {
    @Id
    private String id;
    private int seq;

// getters and setters
}

然后,在插入新条目时(借助Spring MongoDB Repository支持),只需在保存之前像这样设置id字段

BaseQuestion baseQuestion = new BaseQuestion();
baseQuestion.setQuestionId(nextSequenceService.getNextSequence("customSequences"));
/* Rest all values */

baseQuestionRepository.save(baseQuestion);

如果您不喜欢这种方式,则需要使用MongoDBEvents并使用与上述相同的方法使用onBeforeConvert来生成自动值。

同样上述方法也是线程安全的,因为findAndModify()是线程安全的原子方法

2020-05-30