Spring整合MongoDB详细讲解(maven项目)

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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>SpringMongo</groupId>
  <artifactId>SpringMongo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringMongo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.9</version>
      <scope>test</scope>
    </dependency>
    
    <!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
<exclusions>
 <exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
 </exclusion>
</exclusions>
 </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
  </dependencies>
</project>

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

<mongo:mongo id="mongo"  host="127.0.0.1" port="27017">
<!-- 一些连接属性的设置可以不配置用默认的 -->
<mongo:options connections-per-host="64"
threads-allowed-to-block-for-connection-multiplier="100"
connect-timeout="900000" max-wait-time="1200000" auto-connect-retry="true"
socket-keep-alive="true" socket-timeout="1200000" slave-ok="true"
write-number="1" write-timeout="0" write-fsync="true" />
</mongo:mongo>
<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
<mongo:db-factory dbname="test" mongo-ref="mongo" username="" password="" />
<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>

User.java

package com.springmongo.entity;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="users")
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}

}

App.java

package com.springmongo;

import java.util.List;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.springmongo.entity.User;

public class App 
{
private static MongoTemplate template;
static{
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        template = (MongoTemplate) applicationContext.getBean("mongoTemplate");
}
    @Test
    public void findAll(){
    List<User> list = template.findAll(User.class);
    for (User user : list) {
System.out.println(user.toString());
}
    }
    @Test
    public void findAllSortByAge(){
    Query query=new Query();
    query.with(new Sort(new Order(Direction.DESC,"age")));
    List<User> list = template.find(query,User.class);
    for (User user : list) {
System.out.println(user.toString());
}
    }
    @Test
    public void findByCondition(){
    List<User> list = template.find(new Query(Criteria.where("name").is("小宝").
    andOperator(Criteria.where("age").is(301))),
    User.class);
    for (User user : list) {
System.out.println(user.toString());
}
    }
    @Test
    public void limit(){
    List<User> list = template.find(new Query().skip(1).limit(3), User.class);
    for (User user : list) {
System.out.println(user.toString());
}
    }
    @Test
    public void count(){
    long count = template.count(new Query(Criteria.where("name").is("小宝")), User.class);
    System.out.println(count);
    }
    @Test
    public void update(){
    template.updateMulti(new Query(Criteria.where("age").gt(30)),
    new Update().set("name", "小宝"),
    User.class);
    findAll();
    }
    @Test
    public void insert(){
    User user=new User("小奇", 45);
    template.insert(user, "users");
    findAll();
    }
    @Test
    public void delete(){
    template.remove(new Query(Criteria.where("age").is(20)), User.class);
    findAll();
    }
}
发布了101 篇原创文章 · 获赞 58 · 访问量 31万+
展开阅读全文

我的maven项目连接mongodb出现链接异常

12-14

以前还好用,也插入过数据,但是今天就不行了。 项目是maven项目,连接的mongodb在远程服务器上,而且远程服务器的ip和我的ip不在一个网段内, 我改了ip和远程服务器在一个网段后,能ping通远程服务器,但是不能上网了。就出现了mongodb连接超时 具体异常如下 com.mongodb.MongoSocketOpenException: Exception opening socket at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) [mongodb-driver-core-3.1.0.jar:?] at java.lang.Thread.run(Thread.java:745) [?:1.8.0_40] Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[?:1.8.0_40] at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[?:1.8.0_40] at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[?:1.8.0_40] at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[?:1.8.0_40] at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[?:1.8.0_40] at java.net.Socket.connect(Socket.java:589) ~[?:1.8.0_40] at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50) ~[mongodb-driver-core-3.1.0.jar:?] at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.1.0.jar:?] ... 3 more 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览