春季在JPA上利用Mongo实现 [英] Spring utilizing Mongo implementation over JPA

查看:104
本文介绍了春季在JPA上利用Mongo实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Spring框架还很陌生,并且在设置我当前正在研究的项目时遇到了一些麻烦.我需要能够连接到两个不同的数据库,一个是MongoDB,另一个是MSSQL.我正在使用JPA连接到MSSQL.

I am fairly new to the Spring Framework and have been having some trouble setting up the project I am currently working on. I need to be able to connect to two different databases one being MongoDB and the other being MSSQL. I am using JPA to connect to the MSSQL.

我遇到的问题是,当我希望它对MSSQL进行调用时,它似乎正在尝试对Mongo数据库进行调用,而我不确定如何告诉它要读取的内容.我看到过这些帖子建议使用@Qualifier批注将其定向到正确的实现,但是我认为这对我的情况不起作用.

The problem that I am encountering is that it appears to be trying to make calls to the Mongo database when I want it to make calls to the MSSQL and I'm not really sure how to tell it what to read from. I have seen the posts advising to use the @Qualifier annotation to direct it to the correct implementation, but I don't think that that will work for my case.

@RestController
@RequestMapping("/software")
public class SoftwareEndpoint {



    @Autowired
    SoftwareRepository repo;    


    /**********************************************************************************
    ********************************MSSQL calls****************************************
    ***********************************************************************************/
    @RequestMapping(value="/all",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON)
    String getAllSoftware(){

        System.out.println("Here1");
        List<Software> allSoftware = (List<Software>) repo.findAll();
        System.out.println("Here2");
        //rest of method and class

上图显示了我的控制器类的一个片段,其中包含我的SoftwareRepository的一个实例.在db调用之前和之后,我还打印到out流.

Above shows a snippet of my controller class that has an instance of my SoftwareRepository. I also print to the out stream before and after the db call.

输出流仅显示"Here1",然后继续打印以下行:

The out stream only shows "Here1", goes on to print out this line:

2016-10-04 07:35:39.810  INFO 4236 --- [nio-8080-exec-2] org.mongodb.driver.cluster               : No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]}. Waiting for 30000 ms before timing out

,然后在超时时引发异常.

and then throws an exception on timeout.

我没有在本地运行的mongo实例,但是会在其中部署应用程序,但是我不认为这是问题所在,因为在到达该端点时,它不应进行呼叫到Mongo数据库,它应该尝试与MSSQL联系.

I do not have a mongo instance running locally, however there will be on where the application is being deployed, but I don't believe that this is the problem because on hitting that endpoint, it shouldn't be making a call to the Mongo database, it should be trying to reach out to MSSQL.

TLDR:如何指定用于特定存储库或数据库调用的Spring数据库实现?

TLDR: How do I specify which database implementation for Spring to use for a specific repository or database call?

推荐答案

您可以根据上下文中的配置在春季连接到不同的数据库.

You can connect to different databases in spring based on the configuration in context.

以下代码用于连接到MySql和Mongo DB.如果您拥有JDBC,则可以用MSSQL代替MySql.检查 http://jdbforms.sourceforge.net/UsersGuide/html/ch20s02.html了解JDBC连接的属性的含义.

The below code is for connecting to MySql and Mongo DB. You can substitute MySql with MSSQL provided you have the JDBC for it. Check http://jdbforms.sourceforge.net/UsersGuide/html/ch20s02.html for what the properties for JDBC connection mean.

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg ref="mySqldataSource" /> <!-- Change the datasource to MSSQL-->
    </bean>

    <bean id="mySqldataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="removeAbandoned">
            <value>true</value>
        </property>
        <property name="removeAbandonedTimeout">
            <value>30</value>
        </property>
        <property name="driverClassName">
            <value>MSSQL_DRIVER_CLASS_NAME</value>
        </property>
        <property name="url">
            <value>MSSQL_DATABASE_URL</value>
        </property>
        <property name="username">
            <value>MSSQL_DB_USER_NAME</value>
        </property>
        <property name="password">
            <value>MSSQL_DB_PASSWORD</value>
        </property>
        <property name="maxIdle"> 
            <value>10</value>
        </property>
        <property name="maxActive"> 
            <value>10</value>
        </property>
        <property name="maxWait">
            <value>100000</value>
        </property>
        <property name="testOnBorrow">
            <value>false</value>
        </property>
        <property name="testWhileIdle">
            <value>false</value>
        </property>
        <property name="timeBetweenEvictionRunsMillis">
            <value>60000</value>
        </property>
        <property name="minEvictableIdleTimeMillis">
            <value>60000</value>
        </property>
        <property name="numTestsPerEvictionRun">
            <value>1</value>
        </property>
        <property name="defaultTransactionIsolation" value="1" />
        <property name="poolPreparedStatements" value="true" />
        <property name="maxOpenPreparedStatements" value="1" />
    </bean>

    <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"></bean>

下面是用于连接mongodb

Below is for connecting to mongodb

    <mongo:db-factory dbname="mongoDbName" host="mongoServer" port="mongoPort"/>


    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
    <mongo:repositories base-package="com.test.repoPackage"/> <!-- Package containing the mongo repository interfaces -->

现在您可以使用spring提供的存储库.

Now you can use the repositories provided by spring.

.假设config的名称是springConfig.properties.在上面的示例中,针对mongo:db-factory中的属性dbname,host和port,您需要在springConfig.properties中配置这些值.因此,让我们在下面命名它们:

EDIT 1: Suppose name of config is springConfig.properties. In the above example for the properties dbname, host and port in mongo:db-factory, you would want the values to be configured in springConfig.properties. So lets name them below:

mongoServer = xxx.xx.xxx.xxx
mongoPort = 27017
mongoDb = testDb

现在,需要修改上下文文件以导入springConfig.properties.可以在上下文文件中按以下步骤完成此操作:

Now the context file needs to be modified to import the springConfig.properties. this is done as below in the context file:

<bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        <property name="locations" >
            <list>              
                <value>classpath:/log4j.properties</value>
                <value>classpath:/springConfig.properties</value>
            </list>
        </property>
    </bean>

bean mongo:db-factory现在看起来像:

The bean mongo:db-factory would now look like:

<mongo:db-factory dbname="${mongoDb}" host="${mongoServer}" port="${mongoPort}"/>

请注意,配置中的键"(dbname,主机和端口)用insde $ {}表示.这将替换为config中的键值.

Notice that the "keys" from config (dbname, host and port) are represented insde ${}. This will replace with values in config for the keys.

这篇关于春季在JPA上利用Mongo实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆