小明的个人博客
前言:
一: java操作老版本的mongo,insert的参数只能是BasiDBObject,每次想插入数据之前还需要将javaBean转换为DBObject,个人感觉非常麻烦,所以此篇文章使用spring家族提供的MongoTemplate进行讲解示例
二:mongo并没有像mysql那样自带主键自增的效果,虽然有唯一标志ObjectId,但是长度太长在某些场合不合适,所以通过mongo提供的findAndModify原子特性函数进行实现自增ID
1:springMvc+mongo的整合
spring-mvc.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:context="http://www.springframework.org/schema/context"
xmlns:utils="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- TODone: 组件自动扫描配置 -->
<!-- 自动扫描配置 -->
<context:component-scan base-package="com.*"/>
<context:annotation-config />
....其余配置....
//引入mongo.xml配置文件
<import resource="spring-mongo.xml"/>
</beans>
spring-mongo.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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongo.properties" />
<!-- mongo对象 credentials通过账号密码进行身份验证 -->
<mongo:mongo-client id="mongo" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.user}:${mongo.password}@${mongo.dataName}">
<mongo:client-options connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}" />
</mongo:mongo-client>
<mongo:db-factory dbname="${mongo.dataName}" mongo-ref="mongo" id="mongoDbFactory" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
</beans>
mongo.properties:
mongo.host=120.120.120.120
mongo.port=27017
mongo.user=movies
mongo.password=jackies
mongo.dataName=movie
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
#Socket超时时间
mongo.socketTimeout=1500
mongo.slaveOk=true
SeqInfo.java
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* 用于记录主键生成的表
* 序列类
*/
@Getter
@Setter
@NoArgsConstructor
@ToString
@Document(collection = "seqInfo")
public class SeqInfo{
@Id
private String id;// 默认的ObjectId 这个id无实际作用
@Field
private String collName;// 集合名称 相当于表名
@Field
private Long seqId;// 根据collName生成专属的唯一Id值
}
Account.java
import com.spider.annotation.IncKey;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
/**
* @Getter 使用lombok自动生成getter setter方法
*/
@Getter
@Setter
@NoArgsConstructor
@Document(collection = "account")
@ToString
public class Account {
@Field
@ApiModelProperty(value = "用户id")
@IncKey //自定义注解,标识这个字段需要自增
@Id
private Long userId = 0L;
@Field
@ApiModelProperty(value = "用户登陆账号")
private String userName;
@Field
@ApiModelProperty(value = "用户名")
private String userNick;
@Field
@ApiModelProperty(value = "密码")
private String password;
@Field
@ApiModelProperty(value = "权限级别")
private String permissionLevel;
}
IncKey.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标识主键
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface IncKey {
}
2 mongo监听器实现:
SaveEventListener.java
import java.lang.reflect.Field;
import com.spider.annotation.IncKey;
import com.spider.entity.mongoEntity.SeqInfo;
import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
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.util.ReflectionUtils;
import javax.inject.Inject;
/**
* mongo进入真正操作服务器之前会进入这儿,可以做我们想做的初始化操作
*/
public class SaveEventListener extends AbstractMongoEventListener<Object> {
private static Logger logger = Logger.getLogger(SaveEventListener.class);
@Inject
private MongoTemplate mongoTemplate;
/**
* 在发起请求到mongo服务器的前置操作
*/
@Override
public void onBeforeConvert(BeforeConvertEvent<Object> event) {
final Object source = event.getSource();
if (source != null) {
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
// 如果字段添加了我们自定义的IncKey注解
if (field.isAnnotationPresent(IncKey.class)) {
// 通过反射设置自增ID
field.set(source, getNextId(source.getClass().getSimpleName()));
}
}
});
}
}
/**
* 获取下一个自增ID
* 这儿有根据表名进行区分
* @param collName 这里代表数据库表名称
*/
private Long getNextId(String collName) {
Query query = new Query(Criteria.where("collName").is(collName));
Update update = new Update();
update.inc("seqId", 1); //每次自增1
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
//操作SeqInfo表,对其seqId加一并且返回最终值
SeqInfo seq = mongoTemplate.findAndModify(query, update, options, SeqInfo.class);
return seq.getSeqId();
}
}
3 单元测试:
Test.java
@Test
public void testLinstener(){
Account account = new Account();
account.setPassword("111");
account.setPermissionLevel("1");
account.setUserName("chen");
account.setUserNick("xiaominmg");
mongoTemplate.insert(account);
}
运行完成后,数据库会新建2张表 account和seqInfo。account表中的主键名称会默认变成_id,对应的值,就是seqInfo中seqId的最大值。到此结束
END:使用到的jar包
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/io.swagger/swagger-annotations -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
+
Spring那一套 请自行google下载