使用 mongoDB 启动 H2 DB

Posted

技术标签:

【中文标题】使用 mongoDB 启动 H2 DB【英文标题】:Spring boot H2 DB with mongoDB 【发布时间】:2021-02-22 21:47:54 【问题描述】:

当状态设置为“过去”时,我想保存投票结果。 我有一个 H2 数据库,想添加一个只存储结果的 mongoDB。我该如何使用 Spring Boot 实现这一点?

到目前为止,我有一个投票程序,您可以在其中创建投票、编辑投票、投票等。

我已经为 mongodb、spring boot、spring mvc 和 H2 db 等添加了依赖项。

这是我的应用程序属性:

spring.datasource.url=jdbc:h2:file:./db;AUTO_RECONNECT=TRUE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=update

#Mongo Config
spring.main.allow-bean-definition-overriding=true
spring.data.mongodb.database=db-mongo
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost

我已经尝试过制作一个接口 mongoRepository:

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import project.dat250.entity.Poll;
import project.dat250.entity.User;

import java.util.List;

public interface ImongoRepository extends MongoRepository<Poll, Integer>, PagingAndSortingRepository<Poll, Integer> 

    List<Poll> findByNameContainingIgnoreCase(@Param("name") String name);
    List<Poll> findByUser(@Param("user") User user);
    List<Poll> findByIsPublic(@Param("isPublic") boolean isPublic);
    List<Poll> findByStatus(@Param("status") String status);

但添加此存储库后,我收到了数百行错误:

投票类:

@Data
@Entity
public class Poll 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Setter(AccessLevel.PROTECTED)
    private int pollID;
    private String name;
    private String description;
    private boolean isPublic;
    private int voteGreen;
    private int voteRed;
    private String status;
    private int timeLimit;

    @ManyToOne
    private User user;

    @ManyToMany(cascade = CascadeType.PERSIST)
    private List<User> usersVoted = new ArrayList<>();

    public Poll() 
    

    public Poll(String name, String description, boolean isPublic, int voteGreen, int voteRed, String status,
            int timeLimit, User user) 
        this.name = name;
        this.description = description;
        this.isPublic = isPublic;
        this.voteGreen = voteGreen;
        this.voteRed = voteRed;
        this.status = status;
        this.timeLimit = timeLimit;
        this.user = user;
    

    public void setUsersVoted(User userVoted) 
        this.usersVoted.add(userVoted);
    

    public void setUser(User user) 
        this.user = user;
        if (user != null)
            user.setPolls(this);
    

    public void setVoteRed(int red) 
        this.voteRed += red;
    

    public void setVoteGreen(int green) 
        this.voteGreen += green;
    

    public void setPublic(boolean isPublic) 
        this.isPublic = isPublic;
    


【问题讨论】:

你能展示一下 Poll 类吗?\ 添加投票类! Poll 是 JPA 实体类。 MongoRepository 与@Entity 不兼容。应该是@Document 您正在从 H2 数据库表中读取数据并将其写入 MongoDB 数据库集合。读写的过程是什么? 【参考方案1】:

我无法重现您的问题,但我相信这是因为您尝试创建带有 @Entity 注释的类的 @MongoRepository

@MongoRepository 需要一个普通的 POJO 类或带有 @Document 注释的类。

看这个:

package gt.demo64777660;

import lombok.Data;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

@SpringBootApplication
public class DemoApplication 
    public static void main(String[] args) 
        SpringApplication.run(DemoApplication.class, args);
    


interface MongoRepo extends MongoRepository<PollMongo, Integer> 
    List<PollMongo> findByIsPublic(boolean isPublic);


//A:  doesn't work
//interface MongoRepoFromJpaEntity extends MongoRepository<PollJpa, Integer> 
//    List<PollJpa> findByIsPublic(boolean isPublic);
//

interface JPARepo extends JpaRepository<PollJpa, Integer> 
    List<PollJpa> findByIsPublic(boolean isPublic);


//@org.springframework.data.mongodb.core.mapping.Document(collection = "poll") //B: this is optional
@Data
class PollMongo 
//    @org.springframework.data.annotation.Id //B: this is optional
    int id;
    String name;
    boolean isPublic;


@Data
@javax.persistence.Entity
class PollJpa 
    @javax.persistence.Id
    int id;
    String name;
    boolean isPublic;

依赖项(使用 H2 和嵌入式 mongo,无需配置):

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>gt.mobgo</groupId>
    <artifactId>mongo-h2-spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>11</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-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

【讨论】:

以上是关于使用 mongoDB 启动 H2 DB的主要内容,如果未能解决你的问题,请参考以下文章

r 使用slurm启动H2O集群

如何为 H2 查询启动 NamedParameterJdbcTemplate?

使用 rsparkling 在 Databricks 上启动 H2O 上下文

用蚂蚁启动/停止 H2

h2 数据库保留数据但在应用程序启动时重置

h2 和 linux。如何启动数据库?