Preface
The focus of this article is to integrate mongodb and spring into the project, discover problems in practice, track problems, and then solve problems. I won’t say much below, let’s take a look at the detailed introduction together.
1. Preparation
2. Characteristics
3. Dependency package
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.5.0.RELEASE</version></dependency><dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.10</version></dependency>
spring related dependencies
<!-- spring web-related dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.2.RELEASE</version> </dependency> <!-- spring test dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.1.RELEASE</version> </dependency>4. Integrate MongoDB
[Note: Please refer to my article on adding permission management in MongoDB: Enable permission authentication in MongDB]
mongodb.properties
mongo.hostport=172.16.4.166:27017mongo.dbname=ad_api_countmongo.username=hehaitaomongo.password=hehaitaomongo.connectionsPerHost=8mongo.threadsAllowedToBlockForConnectionMultiplier=4#/u8FDE/u63A5/u8D85/u65F6/ u65F6/u95F4mongo.connectTimeout=1000#/u7B49/u5F85/u65F6/u95F4mongo.maxWaitTime=1500mongo.autoConnectRetry=truemongo.socketKeepAlive=true#Socket/u8D85/u65F6/u65F6/u95F4mongo.socketTimeout=1500mongo.slaveOk=true
mongoDB.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-3.1.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- Load the properties configuration file of mongodb --> <context:property-placeholder location="classpath:mongodb.properties" ignore-unresolvable="true"/> <!-- Define the mongo object, corresponding to the Mongo in the official jar package of mongodb. Replica-set set the ip address and port of the cluster replica--> <mongo:mongo id="mongo" replica-set="${mongo.hostport}"> <mongo:options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" auto-connect-retry="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}" socket-timeout="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}" write-number="1" write-timeout="0" write-fsync="true"/> </mongo:mongo> <mongo:db-factory id="mgFactory" dbname="${mongo.dbname}" username="${mongo.username}" password="${mongo.password}" mongo-ref="mongo" /> <bean id="mongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mgFactory"/> </bean></beans>spring-contex.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <aop:aspectj-autopproxy proxy-target-class="true"/> <context:annotation-config/> <!-- Scan all classes under com.lutongnet --> <context:component-scan base-package="com.lutong.cps"> <context:exclude-filter type = "annotation" expression = "org.springframework.steretype.Controller"/> </context:component-scan> <import resource="mongoDB.xml"/> </beans>
5. Code implementation
Basic implementation of MongoDBService
/** * File Name : MongoDBService.java * Package : com.lutongnet.ad.service * Description : TODO * Author : zhangfj * Date : 2012-11-29 * Version : V1.0 */package com.lutong.cps.schedule.service.fj;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Service;/** * @author zhangfj * */@Service("mongoDBService")public class MongoDBService{ /*@Resource(name = "mongoTemplate") protected MongoTemplate mongoTemplate;*/ /** * @param query * @param entityClass * @return T */ public <T> T findOne(Query query, Class<T> entityClass) { ApplicationContext context=new ClassPathXmlApplicationContext("mongoDB.xml"); MongoTemplate mongoTemplate= (MongoTemplate) context.getBean("mongoTemplate"); // You can directly call return mongoTemplate.findOne(query, entityClass); }}Inheriting class UserAdCountService
/** * File Name : UserAdCountService.java * Package : com.lutongnet.ad.service * Description : TODO * Author : zhangfj * Date : 2012-11-29 * Version : V1.0 */package com.lutong.cps.schedule.service.fj;import org.springframework.data.mongodb.core.query.Criteria;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Service;import com.lutong.cps.schedule.entity.UserAdCount;/** * @author zhangfj * */@Service("userAdCountService")public class UserAdCountService extends MongoDBService{ /** * Get the number of views of a single ad, and if it cannot be queried, it will return 0 * * @param adCode * @return int */ public int getUserAdCount(UserAdCount adCode) { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("userAd").is(adCode.getUserAd()), Criteria.where("adCode").is(adCode.getAdCode()), Criteria.where("countDate").is(adCode.getCountDate())); Query query = new Query(criteria); UserAdCount result = findOne(query, UserAdCount.class); if (null != result) { return result.getTimesCount(); } return 0; }}Entity class UserAdCount
package com.lutong.cps.schedule.entity;import java.util.Date;import org.springframework.data.annotation.PersistenceConstructor;import org.springframework.data.mongodb.core.mapping.Document;/** * mongo dedicated statistics on the number of individual ad views of a single user* @author cancer * */@Document(collection="userAdCount")public class UserAdCount{ private int timesCount; /** * User account*/ private String userAd; private String adCode; private String countDate; private Date expireAt;@PersistenceConstructor public UserAdCount(int timesCount, String userAd,String adCode,String countDate,Date expireAt) { this.timesCount = timesCount; this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; this.expireAt = expireAt; } public UserAdCount(String userAd,String adCode,String countDate) { this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; } public UserAdCount(String userAd,String adCode,String countDate,Date expireAt) { this.userAd = userAd; this.adCode = adCode; this.countDate = countDate; this.expireAt = expireAt; } public UserAdCount(String countDate) { this.countDate = countDate; } public int getTimesCount() { return timesCount; } public void setTimesCount(int timesCount) { this.timesCount = timesCount; } public String getUserAd() { return userAd; } public void setUserAd(String userAd) { this.userAd = userAd; } public String getAdCode() { return adCode; } public void setAdCode(String adCode) { this.adCode = adCode; } public String getCountDate() { return countDate; } public void setCountDate(String countDate) { this.countDate = countDate; } public Date getExpireAt() { return expireAt; } public void setExpireAt(Date expireAt) { this.expireAt = expireAt; } }Finally, write a test class to test it
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.lutong.cps.schedule.service.fj.UserAdCountService;@ContextConfiguration({ "classpath:spring-context.xml", "classpath:mongoDB.xml"})@RunWith(SpringJUnit4ClassRunner.class)public class UserTest { @Resource(name = "userAdCountService") private UserAdCountService userAdCountService; @Test public void testDao() { try { UserAdCount userAdCount = new UserAdCount("hehaitao", "pos001", DateTime.now().toString("yyyy-MM-dd")); int count = userAdCountService .getUserAdCount(userAdCount); System.out.println(count); } catch (Exception e) { e.printStackTrace(); } }}Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.