MongoDB默认是没有用户名和密码的,要使用用户名密码,就得为数据库添加用户名
db.createUser(
{
user: "root",
pwd: "root",
roles:
[
{ role: "readWrite", db: "mydb" },
"clusterAdmin"
]
}
)
默认新增数据会有 _class,去掉 _class
import java.util.Arrays;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
@Configuration
public class SpringMongoConfig {
public @Bean MongoTemplate mongoTemplate() throws Exception {
//权限验证 MongoCredential
MongoCredential credential = MongoCredential.createCredential("root", "mydb", "root".toCharArray());
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, "mydb");
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
//不插入_class
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
return mongoTemplate;
}
}
使用上面的类获取MongoTemplate 用来持久化就不会再有“_class”啦。。。。
数据持久化Dao
import java.util.List;
public interface BaseDao {
public void add(T entity) throws Exception;
public void addBatch(List entities) throws Exception;
public void delete(T entity) throws Exception ;
public void update(T query, T update) throws Exception;
public void updateByID(PK id,T entity) throws Exception;
public T findByID(PK id);
public List findAll();
public T findOne(T entity) throws Exception ;
public List find(T entity) throws Exception ;
}
数据持久化DaoImpl
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.springframework.data.annotation.Transient;
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.mongodb.dao.BaseDao;
import com.mongodb.model.SpringMongoConfig;
public class BaseDaoImp<PK extends Serializable, T> implements BaseDao<PK, T> {
@Resource(name = "mongoTemplate")
private MongoTemplate mongoTemplate;
private Class clazz;
@SuppressWarnings("unchecked")
public BaseDaoImp() {
try {
//获取mongoTemplate
if (mongoTemplate==null) {
mongoTemplate = new SpringMongoConfig().mongoTemplate();
}
} catch (Exception e) {
e.printStackTrace();
}
//获取对象的class
clazz = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
}
@Override
public void add(T entity) throws Exception {
mongoTemplate.insert(entity);
}
@Override
public void addBatch(List entities) throws Exception {
mongoTemplate.insertAll(entities);
}
@Override
public void delete(T entity) throws Exception {
Field[] fields = clazz.getDeclaredFields();
Query query = new Query();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(entity);
if (object != null) {
query.addCriteria(new Criteria(field.getName()).is(object));
}
}
mongoTemplate.remove(query,clazz);
}
@Override
public void update(T queryT, T updateT) throws Exception {
Query query = new Query();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(queryT);
if (object != null) {
query.addCriteria(new Criteria(field.getName()).is(object));
}
}
Update update = new Update();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(updateT);
if (object != null) {
update.set(field.getName(), object);
}
}
mongoTemplate.updateMulti(query, update, clazz);
}
@Override
public void updateByID(PK id, T entity) throws Exception {
Field[] fields = clazz.getDeclaredFields();
Update update = new Update();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(entity);
if (object != null) {
update.set(field.getName(), object);
}
}
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)), update, clazz);
}
@Override
public T findByID(PK id) {
return mongoTemplate.findById(id, clazz);
}
@Override
public List findAll() {
return mongoTemplate.findAll(clazz);
}
@Override
public T findOne(T entity) throws Exception {
Field[] fields = clazz.getDeclaredFields();
Query query = new Query();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(entity);
if (object != null) {
query.addCriteria(new Criteria(field.getName()).is(object));
}
}
return mongoTemplate.findOne(query, clazz);
}
@Override
public List find(T entity) throws Exception {
Field[] fields = clazz.getDeclaredFields();
Query query = new Query();
for (Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || field.getName().equalsIgnoreCase("serialVersionUID")) {
continue;
}
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
Method getMthod = pd.getReadMethod();
Object object = getMthod.invoke(entity);
if (object != null) {
query.addCriteria(new Criteria(field.getName()).is(object));
}
}
return mongoTemplate.find(query, clazz);
}
}
mongodb.properties配置文件:
#数据库名称
mongo.dbname = mydb
#密码
mongo.password = root
#用户名
mongo.username = root
#主机
mongo.host = 127.0.0.1
#端口号
mongo.port= 27017
#一个线程变为可用的最大阻塞数
mongo.connectionsPerHost= 8
#线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值
mongo.threadsAllowedToBlockForConnectionMultiplier= 4
#连接超时时间(毫秒)
mongo.connectTimeout= 1500
#最大等待时间
mongo.maxWaitTime= 1500
#自动重连
mongo.autoConnectRetry= true
#scoket保持活动
mongo.socketKeepAlive= true
#scoket超时时间
mongo.socketTimeout=1500
#读写分离
mongo.slaveOk=true
app-context.xml配置文件,与Spring整合
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<import resource="mongo-config.xml" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.springmvc.imooc" />
<mvc:annotation-driven />
beans>
测试:
/*
* 文件名:MongoDBTest.java
* 版权:Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved.
* 描述: MongoDBTest.java
* 修改人:peiyu
* 修改时间:2016年8月3日
* 修改内容:新增
*/
package com.springmvc.imooc.test;
import java.util.List;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.junit.Test;
import com.mongodb.dao.UserDao;
import com.mongodb.dao.impl.UserDaoImpl;
import com.mongodb.model.User;
/**
* @author peiyu
*/
public class MongoDBTest extends BaseTest {
@Test
public void test() throws Exception {
UserDao userDao=new UserDaoImpl();
User user = new User();
user.setAge(10);
user.setId(11221111);
user.setEmail("123@456123123123");
user.setName("name456123123123");
user.setPasword("test456123123123");
List users = userDao.find(user);
System.out.println("----------------新增前-------------------------------------");
for (User user2 : users) {
System.out.println("新增前:"+ReflectionToStringBuilder.toString(user2));
}
userDao.add(user);
users = userDao.find(user);
System.out.println("----------------新增后-------------------------------------");
for (User user2 : users) {
System.out.println("新增后:"+ReflectionToStringBuilder.toString(user2));
}
userDao.delete(user);
users = userDao.find(user);
System.out.println("----------------删除后-------------------------------------");
for (User user2 : users) {
System.out.println("删除后:"+ReflectionToStringBuilder.toString(user2));
}
}
}