好了,前两篇扯了这么多。开始的开始,我们也无须了解的更加深入。重点是要整合到项目中去,在实践中发现问题,追踪问题,然后解决问题。
准备
Maven、Spring(spring-data-mongodb)
spring Data for MongoDB是Spring Data的一个子模块。 目标是为mongodb提供一个相近的一致的基于Spring的编程模型。
Spring Data for MongoDB核心功能是映射POJO到Mongo的DBCollection中的文档,并且提供Repository 风格数据访问层。
特性:
- 可以通过@Configuration注解或者XML风格配置
- MongoTemplate 辅助类 (类似JdbcTemplate),方便常用的CRUD操作
- 异常转换
- 丰富的对象映射
- 通过注解指定对象映射
- 持久化和映射声明周期事件
- 通过MongoReader/MongoWriter 定义底层的映射
- 基于Java的Query, Criteria, Update DSL
- 自动实现Repository,可以提供定制的查找
- QueryDSL 支持类型安全的查询
- 跨数据库平台的持久化 - 支持JPA with Mongo
- GeoSpatial 支持
- Map-Reduce 支持
- JMX管理和监控
- CDI 支持
- GridFS 支持
编程风格
- Spring Data Repository 风格
Spring Data提供了repository 抽象方式,可以极大的减少数据访问层千篇一律的类似的重复的代码。 基本DAO都会实现,find,findAll, findById, save, delete,update等方法,而且代码逻辑基本一致。Spring Data提供了简化方法,通过接口定义 Spring Data通过Proxy自动提供具体的实现。 - MongoTemplate方式
Spring Data for MongoDB还提供了另外一种方式, 类似JdbcTemplate的方式。 这种方式你可以自己定义你的repository的编程方式。 这种方式让你感觉更灵活, 不被上面的各种约定束缚住。你可以通过XML或者JavaConfig方式配置MongoTemplate.
依赖包
把下面的依赖加到pom.xml中的dependencies节点中
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
spring 相关依赖
<!-- spring web相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<!-- spring test依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
集成MongoDB
mongo.properties
#=============#
# mongo #
#=============#
mongo.ip=47.194.212.109
mongo.port=27017
mongo.username=admin
mongo.password=admin
mongo.connections-per-host=2
mongo.max-auto-connect-retry-time=15000L
mongo.threads-allowed-to-block-for-connection-multiplier=4
mongo.connect-timeout=10000
mongo.max-wait-time=15000
mongo.auto-connect-retry=true
mongo.socket-timeout=15000
mongo.slave-ok=true
mongo.write-number=1
mongo.write-timeout=0
mongo.write-fsync=true
spring-context-mongo.xml
<mongo:mongo id="mongo" host="${mongo.ip}" port="${mongo.port}">
<mongo:options connections-per-host="${mongo.connections-per-host}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threads-allowed-to-block-for-connection-multiplier}"
connect-timeout="${mongo.connect-timeout}"
max-wait-time="${mongo.max-wait-time}"
auto-connect-retry="${mongo.auto-connect-retry}"
socket-timeout="${mongo.socket-timeout}"
slave-ok="${mongo.slave-ok}"
write-number="${mongo.write-number}"
write-timeout="${mongo.write-timeout}"
write-fsync="${mongo.write-fsync}" />
</mongo:mongo>
<!-- 用户信息配置 -->
<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
<constructor-arg name="username" value="${mongo.username}"/>
<constructor-arg name="password" value="${mongo.password}"/>
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"/>
<constructor-arg ref="userCredentials" />
<constructor-arg name="databaseName" value="itstyle"/>
</bean>
spring-context.xml
<context:component-scan base-package="com.acts.web.modules" />
<!-- 加載配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:mongo.properties</value>
</list>
</property>
</bean>
代码实现
接口IUserService.java
import java.util.List;
import com.acts.web.modules.mark.model.Users;
/**
* mongodb 案例
* 创建者 张志朋
* 创建时间 2017年7月5日
*
*/
public interface IUserService {
public void saveUser(Users users);
public Users findUserByName(String name);
public void removeUser(String name);
public void updateUser(String name, String key, String value);
public List<Users> listUser();
}
实现UserServiceImpl.java
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
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 org.springframework.stereotype.Service;
import com.acts.web.modules.mark.model.Users;
import com.acts.web.modules.mark.service.IUserService;
@Service(value = "userService")
public class UserServiceImpl implements IUserService {
private static String USER_COLLECTION = "users";
@Autowired
MongoOperations mongoTemplate;
public void saveUser(Users users) {
mongoTemplate.save(users, USER_COLLECTION);
}
public Users findUserByName(String name) {
return mongoTemplate.findOne(
new Query(Criteria.where("name").is(name)), Users.class,
USER_COLLECTION);
}
public void removeUser(String name) {
mongoTemplate.remove(new Query(Criteria.where("name").is(name)),
Users.class, USER_COLLECTION);
}
public void updateUser(String name, String key, String value) {
mongoTemplate.updateFirst(new Query(Criteria.where("name").is(name)),
Update.update(key, value), Users.class);
}
public List<Users> listUser() {
return mongoTemplate.findAll(Users.class);
}
}
实体类Users.java
public class Users {
String uid;
String name;
int age;
public Users(String uid, String name, int age) {
super();
this.uid = uid;
this.name = name;
this.age = age;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
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 "{USERS:{id:" + this.uid + ", name:" + this.name + ",age:"
+ this.age + "}}";
}
}
最后写一个测试类测试一下。
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.acts.web.modules.mark.model.Users;
import com.acts.web.modules.mark.service.IUserService;
@ContextConfiguration({ "classpath:spring-context.xml",
"classpath:spring-context-mongo.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class UserTest {
@Resource
private IUserService userService;
@Test
public void testDao() {
try {
Users users = new Users("1","小明",10);
userService.saveUser(users);
List<Users> list = userService.listUser();
System.out.println(list.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}