Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Spring Boot连接到MongoDB和Postgres_Spring_Mongodb_Postgresql_Spring Boot - Fatal编程技术网

使用Spring Boot连接到MongoDB和Postgres

使用Spring Boot连接到MongoDB和Postgres,spring,mongodb,postgresql,spring-boot,Spring,Mongodb,Postgresql,Spring Boot,我正在同时使用Spring Boot连接MongoDB和Postgres。但是我只能连接到Postgres而不是MongoDB。下面是我正在运行的代码: application.properties: #spring.user.datasource.url=jdbc:mysql://localhost:3306/user #spring.user.datasource.username=root #spring.user.datasource.password=admin

我正在同时使用Spring Boot连接MongoDB和Postgres。但是我只能连接到Postgres而不是MongoDB。下面是我正在运行的代码:

application.properties:

    #spring.user.datasource.url=jdbc:mysql://localhost:3306/user
    #spring.user.datasource.username=root
    #spring.user.datasource.password=admin
    #spring.user.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    #spring.user.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

    mongo.datasource.authentication-database=test
    mongodb.datasource.username=user
    mongodb.datasource.password=pass
    mongodb.datasource.database=test
    mongodb.datasource.port=27017
    mongodb.datasource.host=localhost
    #mongodb.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    mongodb.datasource.uri=mongodb://user:pass@host/test

    spring.booking.datasource.url=jdbc:postgresql://*******/testpost
    spring.booking.datasource.username=user1
    spring.booking.datasource.password=password1
    spring.booking.datasource.driver-class-name=org.postgresql.Driver

    spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true


    #server.tomcat.
    server.port=8800
Postgres配置文件:

package com.devglan.config;`enter code here`

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.devglan.model.Booking;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "bookingEntityManager", 
        transactionManagerRef = "bookingTransactionManager", 
        basePackages = "com.devglan.booking.dao"
)
public class BookingDBConfig {

    @Autowired
    Environment env;

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.booking.datasource")
    public DataSource mysqlDataSource() {
        /*return DataSourceBuilder
                    .create()
                    .build();*/

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.booking.datasource.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.booking.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.booking.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.booking.datasource.password"));

        return dataSource;
    }

    @Primary
    @Bean(name = "bookingEntityManager")
    public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                    .dataSource(mysqlDataSource())
                    .properties(hibernateProperties())
                    .packages(Booking.class)
                    .persistenceUnit("bookingPU")
                    .build();
    }

    @Primary
    @Bean(name = "bookingTransactionManager")
    public PlatformTransactionManager mysqlTransactionManager(@Qualifier("bookingEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Map<String, Object> hibernateProperties() {

        Resource resource = new ClassPathResource("hibernate.properties");

        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            return properties.entrySet().stream()
                                            .collect(Collectors.toMap(
                                                        e -> e.getKey().toString(),
                                                        e -> e.getValue())
                                                    );
        } catch (IOException e) {
            return new HashMap<String, Object>();
        }`enter code here`
    }
}
package com.devglan.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;`enter code here`

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.devglan.model.UserDetails;

@Configuration
@EnableTransactionManagement
@EnableMongoRepositories(basePackages = "com.devglan.user.dao")
        /*
         * entityManagerFactoryRef = "userEntityManager", transactionManagerRef =
         * "userTransactionManager",
         */

public class UserDBConfig {

    @Autowired
    Environment env;

    @Bean
    @ConfigurationProperties(prefix = "mongo.datasource")
    public DataSource postgresqlDataSource() {
        /*return DataSourceBuilder
                    .create()
                    .build();*/

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setUrl(env.getProperty("mongo.datasource.uri"));
        dataSource.setUsername(env.getProperty("mongo.datasource.username"));
        dataSource.setPassword(env.getProperty("mongo.datasource.password"));

        return dataSource;
    }

    @Bean(name = "userEntityManager")
    public LocalContainerEntityManagerFactoryBean postgresqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                    .dataSource(postgresqlDataSource())
                    .properties(hibernateProperties())
                    .packages(UserDetails.class)
                    .persistenceUnit("userPU")
                    .build();
    }

    @Bean(name = "userTransactionManager")
    public PlatformTransactionManager postgresqlTransactionManager(@Qualifier("userEntityManager") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }

    private Map<String, Object> hibernateProperties() {

        Resource resource = new ClassPathResource("hibernate.properties");

        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);

            return properties.entrySet().stream()
                                            .collect(Collectors.toMap(
                                                        e -> e.getKey().toString(),
                                                        e -> e.getValue())
                                                    );
        } catch (IOException e) {
            return new HashMap<String, Object>();
        }
    }
}
但是,Mongo DB连接尚未设置,而我可以连接到postgress

Mongo DB文件根本没有被命中。请帮助,我们将非常感谢您的帮助


我已经在网上阅读了大部分帖子,但似乎没有一篇对我有帮助。

请阅读-总结是,这不是一种向志愿者致辞的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。为什么不使用JPA和Mongo自动配置?请阅读-总结是,这不是解决志愿者问题的理想方式,可能会对获得答案产生反作用。请不要将此添加到您的问题中。为什么不使用JPA和Mongo自动配置?
package com.devglan.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.devglan.model.Booking;
import com.devglan.service.BookingService;

// http://localhost:8800/booking/abc@test.com

@Controller
@RequestMapping("/booking")
public class BookingController {

    @Autowired
    private BookingService bookingService;

    @RequestMapping(value = "/{email:.+}", method = RequestMethod.GET)
    public ResponseEntity<List<Booking>> findUserBookings(@PathVariable(name = "email", value = "email") String email) {

        List<Booking> bookings = bookingService.findUserBookings(email);
        return new ResponseEntity<List<Booking>>(bookings, HttpStatus.OK);
    }

}
package com.devglan.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.devglan.booking.dao.BookingDao;
import com.devglan.model.Booking;
import com.devglan.model.UserDetails;
import com.devglan.service.BookingService;
import com.devglan.user.dao.UserDao;

@Service
public class BookingServiceImpl implements BookingService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private BookingDao bookingDao;

    public List<Booking> findUserBookings(String emailId) {
        UserDetails userdetails = userDao.findByEmail(emailId);
        List<Booking> bookings = bookingDao.findByCreatedBy(userdetails.getId());
        return bookings;
    }
}
  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.0.RELEASE)

    2020-01-06 13:21:45.985  INFO 19024 --- [           main] com.devglan.Application                  : Starting Application on HCBPH0619LP6427 with PID 19024 (D:\Projects\KGIT\workspace\migration\spring-boot-multiple-database-mongo-and-postgres\spring-boot-multiple-database\target\classes started by 143703 in D:\Projects\KGIT\workspace\migration\spring-boot-multiple-database-mongo-and-postgres\spring-boot-multiple-database)
    2020-01-06 13:21:45.993  INFO 19024 --- [           main] com.devglan.Application                  : No active profile set, falling back to default profiles: default
    2020-01-06 13:21:46.114  INFO 19024 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@163370c2: startup date [Mon Jan 06 13:21:46 IST 2020]; root of context hierarchy
    2020-01-06 13:21:47.113  INFO 19024 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
    2020-01-06 13:21:47.217  INFO 19024 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
    2020-01-06 13:21:52.098  INFO 19024 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$fd72a246] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
    2020-01-06 13:21:53.075  INFO 19024 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8800 (http)
    2020-01-06 13:21:53.140  INFO 19024 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2020-01-06 13:21:53.141  INFO 19024 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
    2020-01-06 13:21:53.155  INFO 19024 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_151\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_151/bin/server;C:/Program Files/Java/jre1.8.0_151/bin;C:/Program Files/Java/jre1.8.0_151/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\PuTTY\;C:\Program Files (x86)\Airtame;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\nodejs\;C:\Program Files\Java\jdk1.8.0_151\bin;C:\Users\143703\AppData\Local\Microsoft\WindowsApps;C:\Users\143703\AppData\Local\Programs\Git\cmd;C:\Users\143703\AppData\Roaming\npm;D:\Officials\Softwares\eclipse-jee-2019-03-R-win32-x86_64\eclipse;;.]
    2020-01-06 13:21:53.342  INFO 19024 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2020-01-06 13:21:53.342  INFO 19024 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 7233 ms
    2020-01-06 13:21:53.620  INFO 19024 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2020-01-06 13:21:53.627  INFO 19024 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2020-01-06 13:21:53.628  INFO 19024 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2020-01-06 13:21:53.628  INFO 19024 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2020-01-06 13:21:53.628  INFO 19024 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2020-01-06 13:21:56.363  INFO 19024 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: org.postgresql.Driver
    2020-01-06 13:22:54.692  INFO 19024 --- [           main] o.s.j.d.DriverManagerDataSource          : Loaded JDBC driver: org.postgresql.Driver
    2020-01-06 13:22:58.597  INFO 19024 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'bookingPU'
    2020-01-06 13:22:58.625  INFO 19024 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: bookingPU
        ...]
    2020-01-06 13:22:58.787  INFO 19024 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.2.14.Final}
    2020-01-06 13:22:58.792  INFO 19024 --- [           main] org.hibernate.cfg.Environment            : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.show_sql=true, hibernate.bytecode.use_reflection_optimizer=false, hibernate.format_sql=true}
    2020-01-06 13:22:58.876  INFO 19024 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
    2020-01-06 13:23:01.490  INFO 19024 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
    2020-01-06 13:26:54.812  INFO 19024 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
    2020-01-06 13:26:54.818  INFO 19024 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@1e495414
    2020-01-06 13:26:56.205  INFO 19024 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'bookingPU'