如何使用hibernate和mongodb连接spring boot应用程序。

时间:2018-04-20 09:33:52

标签: java mongodb hibernate spring-boot nosql

我已经开发了一个使用Spring启动,hibernate和mysql的网站。但现在我想连接MongoDB(不使用mysql)。哪个maven依赖需要这样做???其次,我想知道如何将mongodb连接到我的配置。

这是我的pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>lk.slsi</groupId>
    <artifactId>tradeportal</artifactId>
    <packaging>war</packaging>
    <version>slsi-1.1.0-SNAPSHOT</version>
    <name>tradeportal Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <sonar.exclusions>**/public/**/*</sonar.exclusions>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>

        <!--handle servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

        <!--<Email Dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>1.4.3.RELEASE</version>      
        </dependency>
        <!--Add mysql dependency-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.1</version>
        </dependency>
        <!--jasper-->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>3.7.6</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.5.5</version>
            <type>jar</type>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web-services -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
            <version>1.5.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.ws.security/wss4j -->
        <dependency>
            <groupId>org.apache.ws.security</groupId>
            <artifactId>wss4j</artifactId>
            <version>1.6.19</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-libs -->
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-libs</artifactId>
            <version>1.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-security</artifactId>
            <version>2.2.0.RELEASE</version>
            <type>jar</type>
        </dependency>
    </dependencies>
    <build>
        <finalName>tradeportal</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.2</version>
                <configuration>
                    <tagNameFormat>@{project.version}</tagNameFormat>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

这是我的应用程序配置

spring:
  main:
    web-environment: true
    banner-mode: console
  jpa:
    database-platform: org.hibernate.dialect.MySQL5Dialect
    show-sql: true
    hibernate:
      ddl-auto: create
  application:
    name: tradeportal
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/trade_portal_db?createDatabaseIfNotExist=true&useSSL=false
    username: abc
    password: ****

  http:
    multipart:
      max-file-size: 5MB
      max-request-size: 25MB
server:
  port: 8080
  context-path: /tradeportal
tradeportalgov:
  reportData: /reports/images
  # if file path is given relative to the webapp base use INTERNAL if the absolute path is given to baseLocation use EXTERNAL
  # EXTERNAL file download is not implemented
  filePathType : INTERNAL
  filePaths:
    baseLocation: uploads
    vat: va

这是我的Stater

package lk.trad;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.annotation.PreDestroy;

/**
 * Created by ignotus on 1/22/2017.
 */
@SpringBootApplication
@ComponentScan(basePackages = "lk.tradeportal")
@EnableWebMvc
@ImportResource(locations = "classpath:tradeportal-servlet-config.xml")
public class TRADEPORTALStarter extends SpringBootServletInitializer {

    private static final Logger slsiLogger = LogManager.getLogger(TRADEPORTALStarter.class);

    private static ConfigurableApplicationContext context;

    public static void main(String[] args) {
        slsiLogger.info("Starting application");
        SpringApplication application = new SpringApplication(TRADEPORTALStarter.class);
        context = application.run(args);
        application.setRegisterShutdownHook(true);
    }

    @PreDestroy
    private static void closeAppContext(){
        context.close();
    }

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(TRADEPORTALStarter.class);
    }

}

我该怎么办呢。

1 个答案:

答案 0 :(得分:0)

你需要添加2个依赖&#34; spring-boot-starter-data-mongodb&#34;和&#34; spring-boot-starter-data-mongodb-reactive&#34;。

要访问Mongo数据库,您可以注入自动配置的org.springframework.data.mongodb.MongoDbFactory。默认情况下,实例尝试连接到mongodb:// localhost / test上的MongoDB服务器以下示例显示如何连接到MongoDB数据库:

import org.springframework.data.mongodb.MongoDbFactory;
import com.mongodb.DB;

@Component
public class MyBean {

    private final MongoDbFactory mongo;

    @Autowired
    public MyBean(MongoDbFactory mongo) {
        this.mongo = mongo;
    }

    // ...

    public void example() {
        DB db = mongo.getDb();
        // ...
    }

}

您可以设置spring.data.mongodb.uri属性以更改URL并配置其他设置,例如副本集,如以下示例所示:

spring.data.mongodb.uri = mongodb的://用户:secret@mongo1.example.com:12345,mongo2.example.com:23456 /测试 或者,只要您使用Mongo 2.x,就可以指定主机/端口。例如,您可以在application.properties中声明以下设置:

spring.data.mongodb.host = mongoserver spring.data.mongodb.port = 27017

并将spring数据连接到mangodb,您可以使用@Entity注释并为Page或Object设置一个简单的spring数据请求。

import org.springframework.data.domain.*;
import org.springframework.data.repository.*;

public interface CityRepository extends Repository<City, Long> {

    Page<City> findAll(Pageable pageable);

    City findByNameAndCountryAllIgnoringCase(String name, String country);

}