如何通过spring将mongodb中的数据库链接起来

时间:2017-06-15 13:22:07

标签: spring mongodb

我真的需要一些帮助,我经历了整整一天的搜索,但仍然找不到任何有用的东西。

注意:我的数据库有用户名和密码

这两个是我正在使用的依赖项。

<dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.7.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.11.0</version>
        </dependency>
</dependencies>

这是我的xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client  host="address" port="27017 credentials="username:password@databasename" />

</beans>

这是加载此xml的主要类:

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.GenericXmlApplicationContext;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;

    import model.user;
    //import org.springframework.context.support.GenericXmlApplicationContext;

public class App {

    public static void main(String[] args) {
        /*
        ApplicationContext ctx = new AnnotationConfigApplicationContext(appConfig.class);
        MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");
*/

        ApplicationContext ctx = new GenericXmlApplicationContext("config.xml");
        MongoOperations mongoOperation = (MongoOperations)ctx.getBean("mongoTemplate");

        user user = new user();

        // save
        // mongoOperation.save(user);

        // now user object got the created id.
        System.out.println("1. user : " + user);

        // query to search user
        Query searchUserQuery = new Query(Criteria.where("age").is(26));
        mongoOperation.findOne(searchUserQuery, user.class);
    }

}

这是我收到的错误消息:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongo': Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.context.support.GenericXmlApplicationContext.<init>(GenericXmlApplicationContext.java:70)
    at core.App.main(App.java:20)
Caused by: java.lang.NoSuchMethodError: com.mongodb.MongoCredential.createCredential(Ljava/lang/String;Ljava/lang/String;[C)Lcom/mongodb/MongoCredential;
    at org.springframework.data.mongodb.config.MongoCredentialPropertyEditor.setAsText(MongoCredentialPropertyEditor.java:108)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:430)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:403)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:181)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:460)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:512)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:506)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1503)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1462)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1198)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    ... 10 more

1 个答案:

答案 0 :(得分:0)

好的,最后我能够连接到数据库,我是使用MongoClient完成的。这是代码段:

MongoCredential credential = MongoCredential.createMongoCRCredential("username", "database", password);
MongoClient mongoClient = new MongoClient(new ServerAddress("address", 27017), Arrays.asList(credential));

    // get handle to "mydb"
    DB db = mongoClient.getDB("IODS");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }


    // get a collection object to work with
    DBCollection coll = db.getCollection("try_vishal");