Repository: T-baby/MongoDB-Plugin
Branch: master
Commit: 288133bd6877
Files: 40
Total size: 95.7 KB
Directory structure:
gitextract_tlwmmd77/
├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── cybermkd/
│ │ └── mongo/
│ │ ├── constraints/
│ │ │ ├── Chinese.java
│ │ │ ├── Exist.java
│ │ │ ├── Inside.java
│ │ │ └── Type.java
│ │ ├── kit/
│ │ │ ├── MongoBean.java
│ │ │ ├── MongoDocumentKit.java
│ │ │ ├── MongoKit.java
│ │ │ ├── MongoQuery.java
│ │ │ ├── MongoValidate.java
│ │ │ ├── aggregation/
│ │ │ │ ├── MongoAccumulator.java
│ │ │ │ └── MongoAggregation.java
│ │ │ ├── geospatial/
│ │ │ │ └── MongoGeospatial.java
│ │ │ ├── index/
│ │ │ │ └── MongoIndex.java
│ │ │ └── page/
│ │ │ ├── MongoPage.java
│ │ │ └── MongoPaginate.java
│ │ ├── plugin/
│ │ │ ├── MongoIceRestPlugin.java
│ │ │ ├── MongoJFinalPlugin.java
│ │ │ ├── MongoPlugin.java
│ │ │ └── MongoRestyPlugin.java
│ │ └── validation/
│ │ ├── ChineseValidator.java
│ │ ├── ExistValidator.java
│ │ ├── InsideValidator.java
│ │ └── TypeValidator.java
│ └── resources/
│ ├── ValidationMessages.properties
│ └── application.properties
└── test/
├── java/
│ └── com/
│ └── cybermkd/
│ ├── ReadTextTool.java
│ ├── Student.java
│ ├── Teacher.java
│ ├── TestAggregation.java
│ ├── TestCRUD.java
│ ├── TestGeo.java
│ ├── TestMongodb.java
│ ├── TestPage.java
│ └── Time.java
└── resource/
├── student.txt
└── teacher.txt
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
target/
.idea/*
*.iml
*.class
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
#
MongoDB Plugin
[](https://github.com/weibocom/motan/blob/master/LICENSE)
[](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22MongodbPlugin%22)
MongoDB Plugin maybe is the most useful tool in Java and could follow up the real-time official version of ORM, which make you feel comfortable when you are using MongoDB.
Basically synchronous with MongoDB’ version (the latest 3.4.0);
Comfortable usage mode, which is like natural language;
Barely learning cost;
With some features such as supporting MongoDB’s authorization mechanism (Can login with user name and password), bridging copy set of MongoDB, R/ W splitting, write concern, SSL connection and so on.
Built-in JFinal and Resty plugins. (Base on the latest version of JFinal and Resty)
Document:[中文](https://t-baby.gitbooks.io/mongodb-plugin/content/) | [English](https://t-baby.gitbooks.io/mongodb-plugin-english-version/content/)
Maven:[http://search.maven.org/\#search%7Cga%7C1%7Ca%3A%22MongodbPlugin%22](http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22MongodbPlugin%22)
GitHub:[https://github.com/T-baby/MongoDB-Plugin/](https://github.com/T-baby/MongoDB-Plugin/)
Developer:[https://github.com/T-baby/MongoDB-Plugin/](https://github.com/T-baby/MongoDB-Plugin/)
Download:[https://github.com/T-baby/MongoDB-Plugin/releases](https://github.com/T-baby/MongoDB-Plugin/releases)
================================================
FILE: pom.xml
================================================
4.0.0
com.cybermkd
MongodbPlugin
1.0.8.2
jar
MongodbPlugin
帮助JAVA开发者更容易和更舒服使用MongoDB
https://github.com/T-baby/MongoDB-Plugin
Github Issue
https://github.com/T-baby/MongoDB-Plugin/issues
The Apache Software License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0.txt
t-baby
t-baby@zomake.com
CYBERMKD
http://www.cybermkd.com
scm:git@github.com:T-baby/MongoDB-Plugin.git
scm:git@github.com:T-baby/MongoDB-Plugin.git
git@github.com:T-baby/MongoDB-Plugin.git
utf-8
utf-8
junit
junit
4.10
com.jfinal
jfinal
2.2
provided
org.mongodb
mongo-java-driver
3.4.0
com.alibaba
fastjson
1.2.7
cn.dreampie
resty-common
1.0
provided
com.cybermkd
ICEREST
1.0.1.3
provided
ch.qos.logback
logback-classic
1.1.2
org.hibernate
hibernate-validator
5.3.0.Alpha1
javax.el
javax.el-api
2.2.4
org.glassfish.web
javax.el
2.2.4
org.jsoup
jsoup
1.9.2
joda-time
joda-time
2.9.4
MongodbPlugin
org.apache.maven.plugins
maven-jar-plugin
3.0.2
org.apache.maven.plugins
maven-compiler-plugin
3.3
1.6
1.6
release
oss
https://oss.sonatype.org/content/repositories/snapshots/
oss
https://oss.sonatype.org/service/local/staging/deploy/maven2/
org.apache.maven.plugins
maven-source-plugin
2.4
package
jar-no-fork
org.apache.maven.plugins
maven-javadoc-plugin
2.10.3
package
jar
org.apache.maven.plugins
maven-gpg-plugin
1.6
sign-artifacts
verify
sign
org.apache.maven.plugins
maven-compiler-plugin
3.3
1.6
1.6
================================================
FILE: src/main/java/com/cybermkd/mongo/constraints/Chinese.java
================================================
package com.cybermkd.mongo.constraints;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
import com.cybermkd.mongo.validation.ChineseValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ChineseValidator.class)
@Documented
public @interface Chinese {
String message() default "{com.cybermkd.constraints.Chinese.message}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
boolean value();
}
================================================
FILE: src/main/java/com/cybermkd/mongo/constraints/Exist.java
================================================
package com.cybermkd.mongo.constraints;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
import com.cybermkd.mongo.validation.ExistValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ExistValidator.class)
@Documented
public @interface Exist {
String message() default "{com.cybermkd.constraints.Exist.message}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
boolean value();
String collectionName();
String key();
}
================================================
FILE: src/main/java/com/cybermkd/mongo/constraints/Inside.java
================================================
package com.cybermkd.mongo.constraints;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
import com.cybermkd.mongo.validation.InsideValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = InsideValidator.class)
@Documented
public @interface Inside {
String message() default "{com.cybermkd.constraints.Inside.message}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
String[] value();
}
================================================
FILE: src/main/java/com/cybermkd/mongo/constraints/Type.java
================================================
package com.cybermkd.mongo.constraints;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
import com.cybermkd.mongo.validation.TypeValidator;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = TypeValidator.class)
@Documented
public @interface Type {
String message() default "{com.cybermkd.constraints.Type.message}";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
String value();
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/MongoBean.java
================================================
package com.cybermkd.mongo.kit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Map;
/**
* 创建人:T-baby
* 创建日期: 16/7/25
* 文件描述:
*/
public class MongoBean implements Cloneable {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
MongoKit.INSTANCE.error("MongoBean.class", e.getMessage());
}
return this;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
public Map toMap() {
return MongoKit.INSTANCE.toMap(this);
}
public JSONObject toJSONObject() {
return (JSONObject) JSON.toJSON(this);
}
public String toJSONString() {
return JSON.toJSONString(this);
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/MongoDocumentKit.java
================================================
package com.cybermkd.mongo.kit;
import com.cybermkd.mongo.kit.geospatial.MongoGeospatial;
import org.bson.Document;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 创建人:T-baby 创建日期: 2016/12/9 文件描述:
*/
public class MongoDocumentKit {
public static Document toDocument(Object obj) {
Map map;
if (Document.class.isInstance(obj)) {
return (Document) obj;
}
if (!Map.class.isInstance(obj)) {
map = MongoKit.INSTANCE.toMap(obj);
} else {
map = (Map) obj;
}
for (Map.Entry entry : map.entrySet()) {
if (entry.getValue() instanceof MongoGeospatial) {
map.put(entry.getKey(), ((MongoGeospatial) entry.getValue()).getPoint());
}
if (entry.getValue() instanceof MongoBean) {
Document doc = toDocument((MongoBean) entry.getValue());
map.put(entry.getKey(), doc);
}
if (entry.getValue() instanceof List) {
try {
List list = (List) entry.getValue();
List docList = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Document doc = toDocument(list.get(i));
docList.add(doc);
}
map.put(entry.getKey(), docList);
} catch (RuntimeException e) {
MongoKit.INSTANCE.error("MongoDocumentKit.class",
"The list must be List inserted into the database.");
}
}
}
String id = (String) map.get("id");
if (id == null || id.equals("")) {
map.remove("id");
}
return new Document(map);
}
public static Document toDocument(MongoBean bean) {
return new Document(bean.toMap());
}
/* 用于判断是否是基本类型和JSON对象,如果是的话不需要进行转换 */
public static boolean conversionValidation(Object obj) {
if (String.class.isInstance(obj) || Integer.class.isInstance(obj)
|| Double.class.isInstance(obj) || Boolean.class.isInstance(obj)
|| Float.class.isInstance(obj) || Character.class.isInstance(obj)
|| Long.class.isInstance(obj) || Byte.class.isInstance(obj)
|| Short.class.isInstance(obj) || Date.class.isInstance(obj)
|| Map.class.isInstance(obj)) {
return false;
}
if (obj instanceof Object) {
return true;
}
return false;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/MongoKit.java
================================================
package com.cybermkd.mongo.kit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.Block;
import com.mongodb.DBRef;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.InsertManyOptions;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
/**
* 创建人:T-baby
* 创建日期: 16/4/15
* 文件描述:MongoDB操作工具类
*/
public enum MongoKit {
/*
*枚举实现单例模式
*/
INSTANCE;
private static MongoClient client;
private static MongoDatabase defaultDb;
private static Logger logger = LoggerFactory.getLogger(MongoKit.class.getName());
public MongoClient getClient() {
return client;
}
public void init(MongoClient client, String database) {
MongoKit.client = client;
MongoKit.defaultDb = client.getDatabase(database);
}
public MongoCollection getCollection(String collectionName) {
return defaultDb.getCollection(collectionName);
}
public void insert(String collectionName, List docs, InsertManyOptions ops) {
getCollection(collectionName).insertMany(uniding(docs), ops);
}
public void insert(String collectionName, Document doc) {
getCollection(collectionName).insertOne(uniding(doc));
}
public List aggregate(String collectionName, List query, boolean allowDiskUse) {
final List list = new ArrayList();
Block block = new Block() {
public void apply(Document document) {
document = iding(document);
list.add(parseObject(document.toJson()));
}
};
getCollection(collectionName).aggregate(query).allowDiskUse(allowDiskUse).forEach(block);
return list;
}
public List aggregate(String collectionName, List query, boolean allowDiskUse, final Class clazz) {
final List list = new ArrayList();
Block block = new Block() {
public void apply(Document document) {
document = iding(document);
list.add(parseObject(document, clazz));
}
};
getCollection(collectionName).aggregate(query).allowDiskUse(allowDiskUse).forEach(block);
return list;
}
public List find(String collectionName, Bson projection) {
return find(collectionName, new BsonDocument(), new BsonDocument(), projection, 0, 0, "");
}
public List find(String collectionName, int limit, Bson sort, Bson projection) {
return find(collectionName, new BsonDocument(), sort, projection, limit, 0, "");
}
public List find(String collectionName, int limit, int skip, Bson sort, Bson projection, String join) {
return find(collectionName, new BsonDocument(), sort, projection, limit, skip, join);
}
public List find(String collectionName, int limit, Bson sort, Bson projection, Class clazz) {
return find(collectionName, new BsonDocument(), sort, projection, limit, 0, "", clazz);
}
public List find(String collectionName, int limit, int skip, Bson sort, Bson projection, String join, Class clazz) {
return find(collectionName, new BsonDocument(), sort, projection, limit, skip, join, clazz);
}
public List find(String collectionName, Bson query, Bson projection) {
return find(collectionName, query, new BsonDocument(), projection, 0, 0, "");
}
public long count(String collectionName, Bson query) {
return getCollection(collectionName).count(query);
}
public long count(String collectionName) {
return getCollection(collectionName).count();
}
public JSONObject findOne(String collectionName, Bson query, Bson sort, String join) {
return toJSON(
iding(jointing(getCollection(collectionName).find(query).sort(sort).first(), join))
);
}
public T findOne(String collectionName, Bson query, Bson sort, String join, Class clazz) {
return parseObject(
iding(jointing(getCollection(collectionName).find(query).sort(sort).first(), join))
, clazz);
}
public List find(String collectionName, Bson query, Bson sort, Bson projection, int limit,
int skip, final String join) {
final List list = new ArrayList();
Block block = new Block() {
public void apply(Document document) {
document = iding(document);
document = jointing(document, join);
list.add(toJSON(document));
}
};
getCollection(collectionName).find(query).projection(projection).sort(sort).limit(limit).skip(skip).forEach(block);
return list;
}
public List find(String collectionName, Bson query, Bson sort, Bson projection, int limit, int skip,
final String join, final Class clazz) {
final List list = new ArrayList();
Block block = new Block() {
public void apply(Document document) {
document = iding(document);
document = jointing(document, join);
list.add(parseObject(document, clazz));
}
};
getCollection(collectionName).find(query).projection(projection).sort(sort).limit(limit).skip(skip).forEach(block);
return list;
}
public long update(String collectionName, Bson queue, Bson data) {
UpdateResult updateResult = getCollection(collectionName).updateMany(queue, data);
return updateResult.getModifiedCount();
}
public long updateOne(String collectionName, Bson queue, Bson data) {
UpdateResult updateResult = getCollection(collectionName).updateOne(queue, data);
return updateResult.getModifiedCount();
}
public long replaceOne(String collectionName, Bson queue, Document document) {
UpdateResult updateResult = getCollection(collectionName).replaceOne(queue, document);
return updateResult.getModifiedCount();
}
public long delete(String collectionName, Bson queue) {
DeleteResult deleteResult = getCollection(collectionName).deleteMany(queue);
return deleteResult.getDeletedCount();
}
public long deleteOne(String collectionName, Bson queue) {
DeleteResult deleteResult = getCollection(collectionName).deleteOne(queue);
return deleteResult.getDeletedCount();
}
public String validation(Object obj) {
StringBuffer buffer = new StringBuffer(64);//用于存储验证后的错误信息
Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
Set> constraintViolations = validator
.validate(obj);//验证某个对象,其实也可以只验证其中的某一个属性的
Iterator iter = constraintViolations.iterator();
while (iter.hasNext()) {
ConstraintViolation c = (ConstraintViolation) iter.next();
buffer.append(c.getMessage());
}
return buffer.toString();
}
//校验单个属性
public String validation(Object obj, String[] keys) {
StringBuffer buffer = new StringBuffer(64);//用于存储验证后的错误信息
Validator validator = Validation.buildDefaultValidatorFactory()
.getValidator();
Set> constraintViolations = new HashSet>();
for (String key : keys) {
Iterator> it = validator.validateProperty(obj, key).iterator();
if (it.hasNext()) {
constraintViolations.add(it.next());
}
}
Iterator iter = constraintViolations.iterator();
while (iter.hasNext()) {
ConstraintViolation c = (ConstraintViolation) iter.next();
buffer.append(c.getMessage());
}
return buffer.toString();
}
public String setIndex(String collectionName, Bson bson) {
return getCollection(collectionName).createIndex(bson);
}
public List setIndex(String collectionName, List list) {
return getCollection(collectionName).createIndexes(list);
}
public List getIndex(String collectionName) {
final List list = new ArrayList();
Block block = new Block() {
public void apply(final Document document) {
list.add(parseObject(document.toJson()));
}
};
getCollection(collectionName).listIndexes().forEach(block);
return list;
}
public void deleteIndex(String collectionName, Bson bson) {
getCollection(collectionName).dropIndex(bson);
}
public void deleteIndex(String collectionName) {
getCollection(collectionName).dropIndexes();
}
private Document iding(Document document) {
try {
if (document == null || document.get("_id") == null) {
return document;
} else {
document.put("_id", document.get("_id").toString());
}
} catch (ClassCastException e) {
/*如果转换出错直接返回原本的值,不做任何处理*/
}
return document;
}
private List uniding(List list) {
List newList = new ArrayList();
for (Document doc : list) {
newList.add(uniding(doc));
}
return newList;
}
private Document uniding(Document document) {
try {
if (document == null || document.get("_id") == null) {
return document;
} else {
document.remove("_id");
}
} catch (ClassCastException e) {
/*如果转换出错直接返回原本的值,不做任何处理*/
}
return document;
}
private Document jointing(Document document, String join) {
if (join != null && !join.isEmpty()) {
try {
DBRef dbRef = document.get(join, DBRef.class);
Document joinDoc = getCollection(dbRef.getCollectionName())
.find(new Document("_id", dbRef.getId())).first();
joinDoc = iding(joinDoc);
joinDoc.put("id",joinDoc.getString("_id"));
joinDoc.remove("_id");
document.put(join, joinDoc);
} catch (ClassCastException e) {
/*用于避免如果key对应的值并不是DBRef,如果转换出错直接返回原本的值,不做任何处理*/
}
}
return document;
}
/*由于fastjson转换空对象时就会直接抛出异常,而在实际查询中查不到东西是很正常的
* ,所以为了避免会有空异常,特别做了异常处理*/
private JSONObject parseObject(String json) {
try {
if (json != null && !json.isEmpty()) {
return JSON.parseObject(json);
}
return new JSONObject();
} catch (NullPointerException e) {
error("parseObject", json);
return new JSONObject();
}
}
private T parseObject(Document doc, Class clazz) {
try {
if (doc == null) {
return JSON.parseObject(new JSONObject().toJSONString(), clazz);
}
return JSON.parseObject(JSON.toJSONString(doc), clazz);
} catch (NullPointerException e) {
error("parseObject", clazz.getName());
return JSON.parseObject(new JSONObject().toJSONString(), clazz);
}
}
private JSONObject toJSON(Object obj) {
try {
return (JSONObject) JSON.toJSON(obj);
} catch (NullPointerException e) {
error("toJSON", obj.getClass().getName());
return new JSONObject();
}
}
protected void error(String funName, String text) {
logger.error("MongKit tips: (づ ̄ 3 ̄)づ " + funName + " is error ! " + text);
}
public Map toMap(Object obj) {
if(obj == null){
return null;
}
Map map = new HashMap();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
/*过滤class属性 */
if (!key.equals("class")) {
//*得到property对应的getter方法*/
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
MongoKit.INSTANCE.error("MongKit.class","toMap is error " + e.getMessage());
}
return map;
}
public void setDebug(boolean debug) {
ch.qos.logback.classic.Level level;
if (debug) {
level = ch.qos.logback.classic.Level.DEBUG;
} else {
level = ch.qos.logback.classic.Level.WARN;
}
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(level);
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/MongoQuery.java
================================================
package com.cybermkd.mongo.kit;
import com.alibaba.fastjson.JSONObject;
import com.cybermkd.mongo.kit.geospatial.MongoGeospatial;
import com.mongodb.BasicDBObject;
import com.mongodb.DBRef;
import com.mongodb.client.model.*;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Position;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
* 创建人:T-baby
* 创建日期: 16/4/15
* 文件描述:方便增删查改
*/
public class MongoQuery {
private String collectionName;
private String join;
private Document document = new Document();
private List documents = new ArrayList();
private List query = new ArrayList();
private List data = new ArrayList();
private Bson sort;
private Bson projection;
/*用于记录单挑插入时的id*/
private String id;
private int limit = 0;
private int skip = 0;
public String getCollectionName() {
return collectionName;
}
public int getSkip() {
return skip;
}
public int getLimit() {
return limit;
}
public Bson getSort() {
return sort;
}
public MongoQuery use(String name) {
this.collectionName = name;
return this;
}
public static Bson and(List q) {
return q.size() == 0 ? new BsonDocument() : Filters.and((Iterable) q);
}
public MongoQuery or(MongoQuery... qs) {
orQuery(Arrays.asList(qs));
return this;
}
public MongoQuery orQuery(List qs) {
List bsons = new ArrayList();
for (MongoQuery q : qs) {
bsons.add(and(q.getQuery()));
}
query.add(or(bsons));
return this;
}
public static Bson or(List q) {
return q.size() == 0 ? new BsonDocument() : Filters.or((Iterable) q);
}
public static Bson or(Bson q) {
return Filters.or(q);
}
public MongoQuery nor(MongoQuery q) {
query.add(nor(q.getQuery()));
return this;
}
public static Bson nor(List query) {
return query.size() == 0 ? new BsonDocument() : Filters.nor((Iterable) query);
}
public MongoQuery join(String key, String collectionName, String id) {
DBRef ref = new DBRef(collectionName, new ObjectId(id));
document.append(key, ref);
return this;
}
public MongoQuery join(String key) {
this.join = key;
return this;
}
public Document getDocument() {
return this.document;
}
public List getDocuments() {
return this.documents;
}
public List getQuery() {
return this.query;
}
public String getId() {
return id;
}
public List data() {
return this.data;
}
public MongoQuery set(String key, Object value) {
if (MongoDocumentKit.conversionValidation(value)) {
document.append(key, MongoDocumentKit.toDocument(value));
}else {
document.append(key, value);
}
return this;
}
public MongoQuery setGeo(String key, Double x, Double y) {
document.append(key, new Point(new Position(x, y)));
return this;
}
public MongoQuery set(Object obj) {
document = MongoDocumentKit.toDocument(obj);
return this;
}
public MongoQuery add(MongoQuery query) {
documents.add(query.getDocument());
return this;
}
/*用于支持更多原生方法*/
public MongoQuery add(Bson bson) {
data.add(bson);
return this;
}
public MongoQuery filter(Bson filter) {
query.add(filter);
return this;
}
public MongoQuery eq(String key, Object value) {
query.add(Filters.eq(key, value));
return this;
}
public MongoQuery ne(String key, Object value) {
query.add(Filters.ne(key, value));
return this;
}
public MongoQuery regex(String key, String regex) {
query.add(Filters.regex(key, regex));
return this;
}
public MongoQuery type(String key, String type) {
query.add(Filters.type(key, type));
return this;
}
public MongoQuery mod(String key, long divisor, long remainder) {
query.add(Filters.mod(key, divisor, remainder));
return this;
}
public MongoQuery text(String search) {
query.add(Filters.text(search));
return this;
}
public MongoQuery text(String search, TextSearchOptions textSearchOptions) {
query.add(Filters.text(search, textSearchOptions));
return this;
}
public MongoQuery where(String javaScriptExpression) {
query.add(Filters.where(javaScriptExpression));
return this;
}
public MongoQuery elemMatch(String key, MongoQuery query) {
this.query.add(Filters.elemMatch(key, this.and(query.getQuery())));
return this;
}
public MongoQuery size(String key, int size) {
query.add(Filters.size(key, size));
return this;
}
public MongoQuery geo(MongoGeospatial geo) {
query.add(geo.getQuery());
return this;
}
//支持查询id
public MongoQuery in(String key, List values) {
if ("_id".equals(key)) {
List idList = new ArrayList();
Iterator iter = values.iterator();
while (iter.hasNext()) {
Object value = (Object) iter.next();
idList.add(new ObjectId(String.valueOf(value)));
}
query.add(Filters.in(key, idList));
} else {
query.add(Filters.in(key, values));
}
return this;
}
public MongoQuery gt(String key, Object value) {
query.add(Filters.gt(key, value));
return this;
}
public MongoQuery lt(String key, Object value) {
query.add(Filters.lt(key, value));
return this;
}
public MongoQuery gte(String key, Object value) {
query.add(Filters.gte(key, value));
return this;
}
public MongoQuery lte(String key, Object value) {
query.add(Filters.lte(key, value));
return this;
}
public MongoQuery modify(String key, MongoQuery query) {
this.modify(key, query.getDocument());
return this;
}
public MongoQuery modify(String key, Object value) {
if (MongoDocumentKit.conversionValidation(value)) {
data.add(Updates.set(key, MongoDocumentKit.toDocument(value)));
} else {
data.add(Updates.set(key, value));
}
return this;
}
public MongoQuery inc(String key, Number value) {
data.add(Updates.inc(key, value));
return this;
}
public MongoQuery like(String key, String value) {
Pattern pattern = Pattern.compile(value, Pattern.CASE_INSENSITIVE);
query.add(Filters.regex(key, pattern));
return this;
}
//1为以什么开头,2为以什么结尾
public MongoQuery like(int type, String key, String value) {
if (type == 1) {
Pattern pattern = Pattern.compile("^" + value + ".*$", Pattern.CASE_INSENSITIVE);
query.add(Filters.regex(key, pattern));
} else {
Pattern pattern = Pattern.compile("^.*" + value + "$", Pattern.CASE_INSENSITIVE);
query.add(Filters.regex(key, pattern));
}
return this;
}
public MongoQuery byId(String id) {
query.add(new Document("_id", new ObjectId(id)));
return this;
}
public boolean save() {
try {
MongoKit.INSTANCE.insert(collectionName, document);
this.id = this.document.getObjectId("_id").toString();
document.clear();
return true;
} catch (RuntimeException e) {
MongoKit.INSTANCE.error("MongoQuery.class", e.getMessage());
return false;
}
}
public boolean saveList() {
return saveList(false);
}
/*快速插入用于插入不需要排序的文档,如一个人的账户等等*/
public boolean saveList(boolean fast) {
try {
InsertManyOptions ops = new InsertManyOptions();
if (fast) {
ops.ordered(false);
}
MongoKit.INSTANCE.insert(collectionName, documents, ops);
documents.clear();
return true;
} catch (RuntimeException e) {
MongoKit.INSTANCE.error("MongoQuery.class", e.getMessage());
return false;
}
}
public MongoQuery projection(String... keys) {
BasicDBObject dbObj = new BasicDBObject();
for (String key : keys) {
dbObj.append(key, 1);
}
this.projection = dbObj;
return this;
}
public MongoQuery limit(int i) {
this.limit = i;
return this;
}
public MongoQuery skip(int i) {
this.skip = i;
return this;
}
public List findAll() {
return MongoKit.INSTANCE.find(collectionName, limit, skip, sort, projection, join);
}
public List findAll(Class clazz) {
return MongoKit.INSTANCE.find(collectionName, limit, skip, sort, projection, join, clazz);
}
public JSONObject findOne() {
return MongoKit.INSTANCE.findOne(collectionName, and(query), sort, join);
}
public T findOne(Class clazz) {
return MongoKit.INSTANCE.findOne(collectionName, and(query), sort, join, clazz);
}
public List find() {
return MongoKit.INSTANCE.find(collectionName, and(query), sort, projection, limit, skip, join);
}
public List find(Class clazz) {
return MongoKit.INSTANCE.find(collectionName, and(query), sort, projection, limit, skip, join, clazz);
}
public MongoQuery ascending(String... keys) {
this.sort = Sorts.ascending(Arrays.asList(keys));
return this;
}
public MongoQuery descending(String... keys) {
this.sort = Sorts.descending(Arrays.asList(keys));
return this;
}
public long count() {
return MongoKit.INSTANCE.count(collectionName, and(query));
}
public JSONObject max(String key) {
descending(key);
return findOne();
}
public T max(String key, Class clazz) {
descending(key);
return findOne(clazz);
}
public JSONObject min(String key) {
ascending(key);
return findOne();
}
public T min(String key, Class clazz) {
ascending(key);
return findOne(clazz);
}
/*存在某个key*/
public MongoQuery exist(String key) {
set(Filters.exists(key));
return this;
}
/*判断某个值是否存在*/
public boolean exist() {
return this.count() > 0;
}
public long update() {
return MongoKit.INSTANCE.update(collectionName, and(query), Updates.combine(data));
}
public boolean updateOne() {
return MongoKit.INSTANCE.updateOne(collectionName, and(query), Updates.combine(data)) > 0;
}
public long replace(Object obj) {
Document doc = MongoDocumentKit.toDocument(obj);
doc.remove("_id");
return MongoKit.INSTANCE.replaceOne(collectionName, and(query), doc);
}
public long delete() {
return MongoKit.INSTANCE.delete(collectionName, and(query));
}
public boolean deleteOne() {
return MongoKit.INSTANCE.deleteOne(collectionName, and(query)) > 0;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/MongoValidate.java
================================================
package com.cybermkd.mongo.kit;
/**
* 创建人:T-baby
* 创建日期: 2016/12/12
* 文件描述:
*/
public class MongoValidate extends MongoBean{
String validateErrorMessage = "";
public boolean validation() {
validateErrorMessage = MongoKit.INSTANCE.validation(this);
return validateErrorMessage.isEmpty();
}
public boolean validation(String... keys) {
validateErrorMessage = MongoKit.INSTANCE.validation(this, keys);
return validateErrorMessage.isEmpty();
}
public String errorMessage() {
return validateErrorMessage;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/aggregation/MongoAccumulator.java
================================================
package com.cybermkd.mongo.kit.aggregation;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.BsonField;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/8/23
* 文件描述:
*/
public class MongoAccumulator {
private List accumulators = new ArrayList();
public List getAccumulators() {
return accumulators;
}
public MongoAccumulator setAccumulators(List accumulators) {
this.accumulators = accumulators;
return this;
}
public MongoAccumulator sum(String fieldName, String expression) {
accumulators.add(Accumulators.sum(fieldName, expression));
return this;
}
public MongoAccumulator avg(String fieldName, String expression) {
accumulators.add(Accumulators.avg(fieldName, expression));
return this;
}
public MongoAccumulator first(String fieldName, String expression) {
accumulators.add(Accumulators.first(fieldName, expression));
return this;
}
public MongoAccumulator last(String fieldName, String expression) {
accumulators.add(Accumulators.last(fieldName, expression));
return this;
}
public MongoAccumulator max(String fieldName, String expression) {
accumulators.add(Accumulators.max(fieldName, expression));
return this;
}
public MongoAccumulator min(String fieldName, String expression) {
accumulators.add(Accumulators.min(fieldName, expression));
return this;
}
public MongoAccumulator push(String fieldName, String expression) {
accumulators.add(Accumulators.push(fieldName, expression));
return this;
}
public MongoAccumulator addToSet(String fieldName, String expression) {
accumulators.add(Accumulators.addToSet(fieldName, expression));
return this;
}
public MongoAccumulator stdDevPop(String fieldName, String expression) {
accumulators.add(Accumulators.stdDevPop(fieldName, expression));
return this;
}
public MongoAccumulator stdDevSamp(String fieldName, String expression) {
accumulators.add(Accumulators.stdDevSamp(fieldName, expression));
return this;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/aggregation/MongoAggregation.java
================================================
package com.cybermkd.mongo.kit.aggregation;
import com.alibaba.fastjson.JSONObject;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.kit.MongoQuery;
import com.mongodb.client.model.*;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/8/23
* 文件描述:
*/
public class MongoAggregation {
private MongoQuery query;
private List pipeline = new ArrayList();
private List projections = new ArrayList();
private UnwindOptions unwindOptions = new UnwindOptions();
private boolean allowDiskUse = true;
public MongoAggregation(MongoQuery query) {
/*复用MongoQuery*/
this.query = query;
if (query.getQuery() != null && !query.getQuery().isEmpty()) {
pipeline.add(Aggregates.match(Filters.and(query.getQuery())));
}
if (query.getSort() != null) {
pipeline.add(Aggregates.sort(query.getSort()));
}
if (query.getSkip() > 0) {
pipeline.add(Aggregates.skip(query.getSkip()));
}
if (query.getLimit() > 0) {
pipeline.add(Aggregates.limit(query.getLimit()));
}
}
public MongoQuery getQuery() {
return query;
}
public void setQuery(MongoQuery query) {
this.query = query;
}
public void preserveNullAndEmptyArrays(Boolean preserveNullAndEmptyArrays) {
unwindOptions.preserveNullAndEmptyArrays(preserveNullAndEmptyArrays);
}
public MongoAggregation includeArrayIndex(String arrayIndexFieldName) {
unwindOptions.includeArrayIndex(arrayIndexFieldName);
return this;
}
public MongoAggregation unwind(String field) {
pipeline.add(Aggregates.unwind(field, unwindOptions));
return this;
}
public MongoAggregation unwind(String field, UnwindOptions unwindOptions) {
pipeline.add(Aggregates.unwind(field, unwindOptions));
return this;
}
public MongoAggregation projection() {
pipeline.add(Aggregates.project(Projections.fields(projections)));
return this;
}
public MongoAggregation include(String... fieldNames) {
projections.add(Projections.include(fieldNames));
return this;
}
public MongoAggregation exclude(String... fieldNames) {
projections.add(Projections.exclude(fieldNames));
return this;
}
public MongoAggregation excludeId() {
projections.add(Projections.excludeId());
return this;
}
public MongoAggregation sample(int size) {
pipeline.add(Aggregates.sample(size));
return this;
}
public MongoAggregation lookup(String from, String localField, String foreignField, String as) {
pipeline.add(Aggregates.lookup(from, localField, foreignField, as));
return this;
}
public MongoAggregation grahpLookup(String from, TExpression startWith, String connectFromField,
String connectToField, String as, GraphLookupOptions options) {
pipeline.add(Aggregates.graphLookup(from, startWith, connectFromField, connectToField, as, options));
return this;
}
public MongoAggregation out(String collectionName) {
pipeline.add(Aggregates.out(collectionName));
return this;
}
public MongoAggregation group(String fieldName, MongoAccumulator accumulator) {
pipeline.add(Aggregates.group(fieldName, accumulator.getAccumulators()));
return this;
}
public MongoAggregation group(Bson bson) {
pipeline.add(Aggregates.group(bson));
return this;
}
public MongoAggregation addFields(List> fields) {
pipeline.add(Aggregates.addFields(fields));
return this;
}
public MongoAggregation allowDiskUse(boolean allowDiskUse) {
this.allowDiskUse = allowDiskUse;
return this;
}
public MongoAggregation pipeline(Bson bson){
pipeline.add(bson);
return this;
}
public List aggregate() {
return MongoKit.INSTANCE.aggregate(query.getCollectionName(), pipeline, allowDiskUse);
}
public List aggregate(Class clazz) {
return MongoKit.INSTANCE.aggregate(query.getCollectionName(), pipeline, allowDiskUse, clazz);
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/geospatial/MongoGeospatial.java
================================================
package com.cybermkd.mongo.kit.geospatial;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.geojson.Point;
import com.mongodb.client.model.geojson.Position;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 2016/12/13
* 文件描述:
*/
public class MongoGeospatial {
private Point point;
private Bson query;
private List> list = new ArrayList>();
public MongoGeospatial() {
}
public MongoGeospatial(Double x, Double y) {
set(x, y);
}
public MongoGeospatial set(Double x, Double y) {
point = new Point(new Position(x, y));
return this;
}
public MongoGeospatial add(Double x, Double y) {
List temp = new ArrayList();
temp.add(x);
temp.add(y);
list.add(temp);
return this;
}
public Point getPoint() {
return point;
}
public Bson getQuery() {
return query;
}
public List> getList() {
return list;
}
public MongoGeospatial near(String filedName, Double maxDistance, Double minDistance) {
query = Filters.near(filedName, point, maxDistance, minDistance);
return this;
}
public MongoGeospatial nearSphere(String filedName, Double maxDistance, Double minDistance) {
query = Filters.nearSphere(filedName, point, maxDistance, minDistance);
return this;
}
public MongoGeospatial circle(String filedName, Double radius) {
query = Filters.geoWithinCenter(filedName, point.getPosition().getValues().get(0),point.getPosition().getValues().get(1), radius);
return this;
}
public MongoGeospatial circleSphere(String filedName, Double radius) {
query = Filters.geoWithinCenterSphere(filedName, point.getPosition().getValues().get(0),point.getPosition().getValues().get(1), radius);
return this;
}
public MongoGeospatial withinPolygon(String filedName) {
query = Filters.geoWithinPolygon(filedName, list);
return this;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/index/MongoIndex.java
================================================
package com.cybermkd.mongo.kit.index;
import com.alibaba.fastjson.JSONObject;
import com.cybermkd.mongo.kit.MongoKit;
import com.mongodb.client.model.IndexModel;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import org.bson.conversions.Bson;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/8/19
* 文件描述:
*/
public class MongoIndex extends IndexOptions {
private String collectionName;
private Bson bson;
private List indexModels = new ArrayList();
public MongoIndex() {
};
public MongoIndex(String collectionName) {
this.collectionName = collectionName;
}
public Bson getBson() {
return this.bson;
}
/*普通索引*/
public MongoIndex ascending(String... keys) {
this.bson = Indexes.ascending(keys);
return this;
}
public MongoIndex descending(String... keys) {
this.bson = Indexes.descending(keys);
return this;
}
public MongoIndex geo2dsphere(String... keys) {
this.bson = Indexes.geo2dsphere(keys);
return this;
}
public MongoIndex geo2d(String key) {
this.bson = Indexes.geo2d(key);
return this;
}
public MongoIndex geoHaystack(String key, Bson additional) {
this.bson = Indexes.geoHaystack(key, additional);
return this;
}
public MongoIndex text(String key) {
this.bson = Indexes.text(key);
return this;
}
public MongoIndex hashed(String key) {
this.bson = Indexes.hashed(key);
return this;
}
public List get() {
return MongoKit.INSTANCE.getIndex(collectionName);
}
public String save() {
return MongoKit.INSTANCE.setIndex(collectionName, bson);
}
public void delete() {
MongoKit.INSTANCE.deleteIndex(collectionName, bson);
}
public void deleteAll() {
MongoKit.INSTANCE.deleteIndex(collectionName);
}
/*组合索引*/
public MongoIndex add(MongoIndex mongoIndex) {
indexModels.add(new IndexModel(Indexes.compoundIndex(mongoIndex.getBson()), mongoIndex));
return this;
}
public List compound() {
return MongoKit.INSTANCE.setIndex(collectionName, indexModels);
}
/*设置*/
public MongoIndex setUnique(boolean unique) {
unique(unique);
return this;
}
public MongoIndex setBackground(boolean background) {
background(background);
return this;
}
public MongoIndex setSparse(boolean sparse) {
sparse(sparse);
return this;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/page/MongoPage.java
================================================
package com.cybermkd.mongo.kit.page;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/5/19
* 文件描述:
*/
public class MongoPage {
private int count;
private int page;
private int totalPage;
private long totalRow;
private boolean firstPage = false;
private boolean lastPage = false;
private List list = new ArrayList();
public MongoPage(int count, int page, int totalPage, long totalRow, boolean firstPage,
boolean lastPage, List result) {
this.count = count;
this.page = page;
this.totalPage = totalPage;
this.totalRow = totalRow;
this.firstPage = firstPage;
this.lastPage = lastPage;
this.list = result;
}
public int getCount() {
return count;
}
public int getPage() {
return page;
}
public int getTotalPage() {
return totalPage;
}
public long getTotalRow() {
return totalRow;
}
public boolean isFirstPage() {
return firstPage;
}
public boolean isLastPage() {
return lastPage;
}
public List getList() {
return list;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/kit/page/MongoPaginate.java
================================================
package com.cybermkd.mongo.kit.page;
import com.alibaba.fastjson.JSONObject;
import com.cybermkd.mongo.kit.MongoQuery;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/5/17
* 文件描述:用于分页
*/
public class MongoPaginate {
private int count;
private int page;
private int totalPage;
private long totalRow;
private MongoQuery query;
private boolean firstPage = false;
private boolean lastPage = false;
private List list = new ArrayList();
public MongoPaginate(MongoQuery query, int count, int page) {
this.query = query;
this.count = count;
this.page = page;
this.totalRow = count();
this.totalPage = (int) (totalRow / (long) count);
if (totalRow % (long) count != 0L) {
++totalPage;
}
if (count > totalRow) {
this.count = (int) totalRow;
}
if (totalRow != 0 && this.count <= 0 || this.page <= 0) {
throw new RuntimeException("MongPage tips: (づ ̄ 3 ̄)づ count or page is error !");
}
this.firstPage = this.page == 1;
this.lastPage = this.page == this.totalPage;
}
public MongoPage find() {
this.list = query.limit(count).skip(skip()).find();
return new MongoPage(count, page, totalPage, totalRow, firstPage, lastPage, list);
}
public MongoPage find(Class clazz) {
this.list = query.limit(count).skip(skip()).find(clazz);
return new MongoPage(count, page, totalPage, totalRow, firstPage, lastPage, list);
}
public MongoPage findAll() {
this.list = query.limit(count).skip(skip()).findAll();
return new MongoPage(count, page, totalPage, totalRow, firstPage, lastPage, list);
}
public MongoPage findAll(Class clazz) {
this.list = query.limit(count).skip(skip()).findAll(clazz);
return new MongoPage(count, page, totalPage, totalRow, firstPage, lastPage, list);
}
private int skip() {
if (firstPage) {
return 0;
} else {
return (page - 1) * count;
}
}
public int count() {
return (int) this.query.count();
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/plugin/MongoIceRestPlugin.java
================================================
package com.cybermkd.mongo.plugin;
import com.cybermkd.common.Plugin;
import com.cybermkd.mongo.kit.MongoKit;
import com.mongodb.MongoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 创建人:T-baby
* 创建日期: 16/4/17
* 文件描述:MongoDB for Resty 插件
*/
public class MongoIceRestPlugin extends MongoPlugin implements Plugin {
final Logger logger = LoggerFactory.getLogger(MongoIceRestPlugin.class);
private MongoClient client;
@Override
public boolean start() {
client = getMongoClient();
MongoKit.INSTANCE.init(client, getDatabase());
return true;
}
@Override
public boolean stop() {
if (client != null) {
client.close();
}
return true;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/plugin/MongoJFinalPlugin.java
================================================
package com.cybermkd.mongo.plugin;
import com.cybermkd.mongo.kit.MongoKit;
import com.jfinal.plugin.IPlugin;
import com.mongodb.MongoClient;
import java.util.logging.Logger;
/**
* 创建人:T-baby
* 创建日期: 16/4/15
* 文件描述:MongoDB for JFinal 插件
*/
public class MongoJFinalPlugin extends MongoPlugin implements IPlugin {
protected final Logger logger = Logger.getLogger(this.getClass().getName());
private MongoClient client;
@Override
public boolean start() {
client = getMongoClient();
MongoKit.INSTANCE.init(client, getDatabase());
return true;
}
@Override
public boolean stop() {
if (client != null) {
client.close();
}
return true;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/plugin/MongoPlugin.java
================================================
package com.cybermkd.mongo.plugin;
import com.cybermkd.mongo.kit.MongoKit;
import com.mongodb.*;
import java.util.ArrayList;
import java.util.List;
/**
* 创建人:T-baby
* 创建日期: 16/5/13
* 文件描述:支持更多特性的MongoPlugin
*/
public class MongoPlugin {
private MongoClientOptions.Builder options = MongoClientOptions.builder();
private List hostList = new ArrayList();
private List authList = new ArrayList();
/*数据库名*/
private String database;
public MongoPlugin add(String host) {
this.hostList.add(new ServerAddress(host, 27017));
return this;
}
public MongoPlugin add(String host, int port) {
this.hostList.add(new ServerAddress(host, port));
return this;
}
public MongoPlugin setDatabase(String database) {
this.database = database;
return this;
}
public String getDatabase() {
return this.database;
}
/*数据库授权*/
public MongoPlugin auth(MongoCredential mongoCredential) {
this.authList.add(mongoCredential);
return this;
}
/*数据库授权*/
public MongoPlugin auth(String username, String password) {
this.authList.add(MongoCredential.createScramSha1Credential(username, this.database, password.toCharArray()));
return this;
}
public MongoPlugin authCR(String username, String password) {
this.authList.add(MongoCredential.createMongoCRCredential(username, this.database, password.toCharArray()));
return this;
}
public MongoPlugin authX509(String x509) {
this.authList.add(MongoCredential.createMongoX509Credential(x509));
return this;
}
/*SSL*/
public MongoPlugin ssl() {
this.options.sslEnabled(true);
return this;
}
public MongoPlugin connectTimeout(int connectTimeout) {
this.options.connectTimeout(connectTimeout);
return this;
}
public MongoPlugin opition(MongoClientOptions.Builder opitions) {
this.options = opitions;
return this;
}
/*自定义读写分离
* primary
* 主节点,默认模式,读操作只在主节点,如果主节点不可用,报错或者抛出异常。
* primaryPreferred
* 首选主节点,大多情况下读操作在主节点,如果主节点不可用,如故障转移,读操作在从节点。
* secondary
* 从节点,读操作只在从节点, 如果从节点不可用,报错或者抛出异常。
* secondaryPreferred
* 首选从节点,大多情况下读操作在从节点,特殊情况(如单主节点架构)读操作在主节点。
* nearest
* 最邻近节点,读操作在最邻近的成员,可能是主节点或者从节点,根据ping时间最短
* */
public MongoPlugin readPreference(ReadPreference readPreference) {
this.options.readPreference(readPreference);
return this;
}
public MongoPlugin readPreference() {
this.options.readPreference(ReadPreference.secondaryPreferred());
return this;
}
public MongoPlugin writeConcern(WriteConcern writeConcern) {
this.options.writeConcern(writeConcern);
return this;
}
/*前几次修改操作仍然被记录在journal中,可以被还原也可以被撤销,避免数据不一致或弄脏的情况,写成功后再执行到真的数据集中*/
public MongoPlugin writeConcern() {
this.options.writeConcern(WriteConcern.JOURNALED);
return this;
}
/*在分布式下写到多个节点后才进行返回*/
public MongoPlugin writeSafe() {
this.options.writeConcern(WriteConcern.MAJORITY);
return this;
}
/*如果不是debug模式可以关闭日志*/
public MongoPlugin setDebug(boolean debug) {
MongoKit.INSTANCE.setDebug(debug);
return this;
}
public MongoClient getMongoClient() {
try {
return new MongoClient(hostList, authList, options.build());
} catch (Exception e) {
throw new RuntimeException("无法连接mongodb,请检查配置!Can't connect mongodb!");
}
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/plugin/MongoRestyPlugin.java
================================================
package com.cybermkd.mongo.plugin;
import cn.dreampie.common.Plugin;
import com.cybermkd.mongo.kit.MongoKit;
import com.mongodb.MongoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 创建人:T-baby
* 创建日期: 16/4/17
* 文件描述:MongoDB for Resty 插件
*/
public class MongoRestyPlugin extends MongoPlugin implements Plugin {
final Logger logger = LoggerFactory.getLogger(MongoRestyPlugin.class);
private MongoClient client;
@Override
public boolean start() {
client = getMongoClient();
MongoKit.INSTANCE.init(client, getDatabase());
return true;
}
@Override
public boolean stop() {
if (client != null) {
client.close();
}
return true;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/validation/ChineseValidator.java
================================================
package com.cybermkd.mongo.validation;
import com.cybermkd.mongo.constraints.Chinese;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
public class ChineseValidator implements ConstraintValidator {
private boolean value = false;
@Override
public void initialize(Chinese chinese) {
value = chinese.value();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (value) {
return isChinese(s);
} else {
return !isChinese(s);
}
}
// 根据Unicode编码判断中文汉字和符号
private static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
return true;
}
return false;
}
// 判断中文汉字和符号
public static boolean isChinese(String strName) {
char[] ch = strName.toCharArray();
for (int i = 0; i < ch.length; i++) {
char c = ch[i];
if (isChinese(c)) {
return true;
}
}
return false;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/validation/ExistValidator.java
================================================
package com.cybermkd.mongo.validation;
import com.cybermkd.mongo.constraints.Exist;
import com.cybermkd.mongo.kit.MongoQuery;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
public class ExistValidator implements ConstraintValidator {
private boolean value = false;
private String collectionName = "";
private String key = "";
@Override
public void initialize(Exist exist) {
value = exist.value();
collectionName = exist.collectionName();
key = exist.key();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (value) {
return exist(s);
}
return !exist(s);
}
private boolean exist(String s) {
MongoQuery query = new MongoQuery().use(collectionName);
if (key.equals("id") || key.equals("_id")) {
query.byId(s);
} else {
query.eq(key, s);
}
return query.exist();
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/validation/InsideValidator.java
================================================
package com.cybermkd.mongo.validation;
import com.cybermkd.mongo.constraints.Inside;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
public class InsideValidator implements ConstraintValidator {
private String[] value;
@Override
public void initialize(Inside inside) {
value = inside.value();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
for (String text : value) {
if (text.equals(s)) {
return true;
}
}
return false;
}
}
================================================
FILE: src/main/java/com/cybermkd/mongo/validation/TypeValidator.java
================================================
package com.cybermkd.mongo.validation;
import com.cybermkd.mongo.constraints.Type;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 创建人:T-baby
* 创建日期: 16/8/3
* 文件描述:
*/
public class TypeValidator implements ConstraintValidator {
private String value = "string";
@Override
public void initialize(Type type) {
value = type.value();
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (value.equals("int")) {
return isInt(s);
} else if (value.equals("double")) {
return isDouble(s);
} else if (value.equals("boolean")) {
return isDouble(s);
} else {
return true;
}
}
private boolean isInt(String s) {
Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(s);
return mer.find();
}
private boolean isDouble(String s) {
Matcher mer = Pattern.compile("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$").matcher(s);
return mer.find();
}
private boolean isBoolean(String s) {
return s.equals("true") || s.equals("false");
}
}
================================================
FILE: src/main/resources/ValidationMessages.properties
================================================
com.cybermkd.mongo.constraints.Chinese.message=${validatedValue} must ${value == true ? 'be chinese' : ' not be chinese'}
com.cybermkd.mongo.constraints.Type.message=${validatedValue} must be {value}
com.cybermkd.mongo.constraints.Inside.message=${validatedValue} must be in {value}
com.cybermkd.mongo.constraints.Exist.message=${validatedValue} ${value == true ? 'must be exist' : 'must not repeat '}
================================================
FILE: src/main/resources/application.properties
================================================
#not must auto load
app.encoding=UTF-8
app.devMode=true
================================================
FILE: src/test/java/com/cybermkd/ReadTextTool.java
================================================
package com.cybermkd;
/**
* 创建人:T-baby
* 创建日期: 16/5/5
* 文件描述:
*/
import com.alibaba.fastjson.JSONArray;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class ReadTextTool {
/**
* 功能:Java读取txt文件的内容
* 步骤:1:先获得文件句柄
* 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
* 3:读取到输入流后,需要读取生成字节流
* 4:一行一行的输出。readline()。
* 备注:需要考虑的是异常情况
* @param filePath
*/
public static JSONArray readTxtFile(String filePath){
try {
String encoding="UTF-8";
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
JSONArray jsonArray=new JSONArray();
while((lineTxt = bufferedReader.readLine()) != null){
jsonArray.add(lineTxt);
}
read.close();
return jsonArray;
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
return null;
}
//xxx.class.getResource("/configs/interface/....");
}
================================================
FILE: src/test/java/com/cybermkd/Student.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.annotation.JSONField;
import com.cybermkd.mongo.constraints.Chinese;
import com.cybermkd.mongo.constraints.Exist;
import com.cybermkd.mongo.constraints.Inside;
import com.cybermkd.mongo.constraints.Type;
import com.cybermkd.mongo.kit.MongoValidate;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.SafeHtml;
import javax.validation.constraints.Size;
/**
* 创建人:T-baby
* 创建日期: 16/8/25
* 文件描述:
*/
public class Student extends MongoValidate {
/**
* Student是一个英语培训机构的学生类,因为MongoDB本身没有约束,故使用class来约束
*
* @param id Objectid
* @param name 学生姓名
* @param age 学生年龄
* @param sex 学生性别,1为男生,2为女生
* @param score 几次考试总数
* @param teacher 教课的老师
*/
@Exist(value = false, collectionName = "student", key = "id")
private String id;
@Chinese(value = true)
@Size(min = 1, max = 4)
@SafeHtml
private String name;
@Type(value = "int")
@Size(min = 1, max = 100)
private int age;
@Type(value = "int")
@Inside(value = {"1", "2"})
private int sex;
@Length(max = 100)
private int score;
private Teacher teacher;
private String teacherName;
private Time time= new Time();
public String getId() {
return id;
}
@JSONField(name = "_id")
public void setId(String id) {
this.id = id;
}
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;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
}
================================================
FILE: src/test/java/com/cybermkd/Teacher.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.annotation.JSONField;
import com.cybermkd.mongo.constraints.Chinese;
import org.hibernate.validator.constraints.SafeHtml;
import javax.validation.constraints.Size;
/**
* 创建人:T-baby
* 创建日期: 16/8/25
* 文件描述:
*/
public class Teacher {
/**
* Teacher是一个英语培训机构的老师类,因为MongoDB本身没有约束,故使用class来约束
* @param id Objectid
* @param name 老师姓名
*/
private String id;
@Chinese(value = true)
@Size(min = 1,max = 4)
@SafeHtml
private String name;
public String getId() {
return id;
}
@JSONField(name = "_id")
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
================================================
FILE: src/test/java/com/cybermkd/TestAggregation.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.JSON;
import com.cybermkd.mongo.kit.aggregation.MongoAggregation;
import com.cybermkd.mongo.kit.MongoQuery;
import org.junit.Test;
/**
* 创建人:T-baby
* 创建日期: 16/8/26
* 文件描述:
*/
public class TestAggregation extends TestMongodb {
/*求出每个老师下所有男生平均成绩,输出到output集合中*/
@Test
public void avg(){
MongoQuery query=new MongoQuery();
//query.use("student").eq("sex",1).descending("age").limit(10);
query.use("student").eq("sex",1).descending("score");
MongoAggregation aggregation=new MongoAggregation(query);
logger.info(JSON.toJSONString(aggregation
.include("name","sex","age","teacherName")
.projection()
//.lookup("teacher","teacherName","name","teacher")
//.group("$teacherName",new MongoAccumulator().avg("result","$age"))
//.out("_output_")
.aggregate(Student.class)));
}
}
================================================
FILE: src/test/java/com/cybermkd/TestCRUD.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.JSON;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.kit.MongoQuery;
import org.junit.Test;
/**
* 创建人:T-baby
* 创建日期: 16/8/26
* 文件描述:
*/
public class TestCRUD extends TestMongodb {
private static String id;
@Test
public void debug(){
MongoKit.INSTANCE.setDebug(false);
}
@Test
public void insert(){
MongoQuery query=new MongoQuery();
Teacher teacher=new Teacher();
teacher.setName("踢宝宝");
query.use("teacher").set(teacher).save();
id=query.getId();
logger.info(id);
}
@Test
public void findOne(){
MongoQuery query=new MongoQuery();
logger.info(query.use("teacher").byId(id).findOne().toJSONString());
}
@Test
public void findOr(){
MongoQuery query=new MongoQuery();
logger.info(JSON.toJSONString(query.use("teacher").or(new MongoQuery().eq("name","卫越相"),new MongoQuery().eq("name","危兴修")).find()));
}
@Test
public void findAndJoin(){
MongoQuery query=new MongoQuery();
logger.info(JSON.toJSONString(query.use("student").join("teacher").findOne(Student.class)));
}
@Test
public void update(){
logger.info(new MongoQuery().use("teacher").eq("name","卫越相").findOne().toJSONString());
logger.info(String.valueOf(new MongoQuery().use("teacher").eq("name","卫越相").modify("name","兔宝宝").update()));
logger.info(new MongoQuery().use("teacher").eq("name","兔宝宝").findOne().toJSONString());
}
@Test
public void delete(){
Teacher teacher=new MongoQuery().use("teacher").eq("name","兔宝宝").findOne(Teacher.class);
logger.info(String.valueOf(new MongoQuery().use("teacher").byId(teacher.getId()).deleteOne()));
}
@Test
public void sort(){
logger.info(JSON.toJSONString(new MongoQuery().use("student").descending("age").join("teacher").findAll()));
}
@Test
public void count(){
logger.info(JSON.toJSONString(new MongoQuery().use("student").count()));
}
@Test
public void max(){
logger.info(JSON.toJSONString(new MongoQuery().use("student").join("teacher").max("age")));
}
@Test
public void min(){
logger.info(JSON.toJSONString(new MongoQuery().use("student").join("teacher").min("age")));
}
@Test
public void exit(){
logger.info(String.valueOf(new MongoQuery().use("student").eq("name","贝承载").exist()));
}
}
================================================
FILE: src/test/java/com/cybermkd/TestGeo.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.JSON;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.kit.MongoQuery;
import com.cybermkd.mongo.kit.geospatial.MongoGeospatial;
import com.cybermkd.mongo.kit.index.MongoIndex;
import com.cybermkd.mongo.plugin.MongoPlugin;
import com.mongodb.MongoClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* 创建人:T-baby
* 创建日期: 2016/12/13
* 文件描述:
*/
public class TestGeo {
@Before
public void init() {
MongoPlugin plugin = new MongoPlugin();
plugin.add("127.0.0.1", 27017).setDatabase("map");
MongoClient client = plugin.getMongoClient();
MongoKit.INSTANCE.init(client, plugin.getDatabase());
}
@Test
public void testInsert() {
MongoQuery query = new MongoQuery().use("point");
query.add(new MongoQuery().set("name", "深圳大学").setGeo("geo", 113.9365065988, 22.5350151812));
query.add(new MongoQuery().set("name", "豪方精品酒店公寓").setGeo("geo", 113.9341400000, 22.5311710000));
query.add(new MongoQuery().set("name", "深圳市深大制冷电器有限公司").setGeo("geo", 113.9214880000, 22.5332620000));
query.add(new MongoQuery().set("name", "深圳职业技术学院").setGeo("geo", 113.9466750000, 22.5873010000));
System.out.println(query.saveList(true));
}
@Test
public void testIndex() {
MongoIndex index = new MongoIndex("point");
System.out.println(index.geo2dsphere("geo").save());
}
@Test
public void testNear() {
MongoQuery query = new MongoQuery().use("point");
MongoGeospatial geo = new MongoGeospatial(113.9365065988, 22.5350151812).circleSphere("geo", 5000.0);
query.geo(geo);
System.out.println(JSON.toJSONString(query.find()));
}
@After
public void close() {
MongoKit.INSTANCE.getClient().close();
}
}
================================================
FILE: src/test/java/com/cybermkd/TestMongodb.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.JSONArray;
import com.cybermkd.log.Logger;
import com.cybermkd.mongo.kit.MongoKit;
import com.cybermkd.mongo.kit.MongoQuery;
import com.cybermkd.mongo.plugin.MongoPlugin;
import com.mongodb.MongoClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.util.Random;
/**
* 创建人:T-baby
* 创建日期: 16/8/25
* 文件描述:
*/
public class TestMongodb {
private static final Random random = new Random();
public static Logger logger = Logger.getLogger(TestMongodb.class);
@BeforeClass
public static void init() {
MongoPlugin plugin = new MongoPlugin();
plugin.add("127.0.0.1", 27017).setDatabase("training");
MongoClient client = plugin.getMongoClient();
MongoKit.INSTANCE.init(client, plugin.getDatabase());
MongoKit.INSTANCE.getCollection("_output_").drop();
MongoKit.INSTANCE.getCollection("student").drop();
MongoKit.INSTANCE.getCollection("teacher").drop();
/*开始模拟真实数据*/
JSONArray studentNames = ReadTextTool.readTxtFile(TestMongodb.class.getResource("/student.txt").getPath());
JSONArray teacherNames = ReadTextTool.readTxtFile(TestMongodb.class.getResource("/teacher.txt").getPath());
/*每个老师带十个学生*/
for (int i = 0; i < 100; i++) {
/*初始化批量插入用的对象*/
MongoQuery teacherQuery = new MongoQuery().use("teacher");
MongoQuery studentQuery = new MongoQuery().use("student");
Teacher teacher = new Teacher();
teacher.setName(spaceFliter(teacherNames.getString(i)));
teacherQuery.set(teacher);
teacherQuery.save();
for (int j = 0; j < 10; j++) {
Student student = new Student();
student.setName(spaceFliter(studentNames.getString(10 * i + j)));
student.setAge(number(18, 30));
student.setSex(sex(student.getAge()));
student.setScore(number(0,100));
student.setTeacherName(teacher.getName());
studentQuery.add(new MongoQuery().set(student).join("teacher", "teacher", teacherQuery.getId()));
}
studentQuery.saveList();
}
}
@AfterClass
public static void clean() {
MongoKit.INSTANCE.getCollection("_output_").drop();
MongoKit.INSTANCE.getCollection("student").drop();
MongoKit.INSTANCE.getCollection("teacher").drop();
MongoKit.INSTANCE.getClient().close();
}
public static int number(int min, int max) {
return min + random.nextInt(max - min);
}
public static int sex(int age) {
if (age % 2 == 0) {
return 1;
}else {
return 2;
}
}
//用于去掉空格
public static String spaceFliter(String text) {
text = text.replaceAll(" ", "");
return text;
}
}
================================================
FILE: src/test/java/com/cybermkd/TestPage.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.JSON;
import com.cybermkd.mongo.kit.page.MongoPaginate;
import com.cybermkd.mongo.kit.MongoQuery;
import org.junit.Test;
/**
* 创建人:T-baby
* 创建日期: 16/8/26
* 文件描述:
*/
public class TestPage extends TestMongodb {
@Test
public void page(){
MongoPaginate page=new MongoPaginate(new MongoQuery().use("student").descending("age").join("teacher"),20,1);
logger.info(JSON.toJSONString(page.findAll(Student.class)));
}
}
================================================
FILE: src/test/java/com/cybermkd/Time.java
================================================
package com.cybermkd;
import com.alibaba.fastjson.annotation.JSONField;
import com.cybermkd.mongo.kit.MongoValidate;
import java.util.Date;
public class Time extends MongoValidate{
@JSONField(format="yyyy-MM-dd HH:mm:ss")
private Date date=new Date();
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
================================================
FILE: src/test/resource/student.txt
================================================
燕夏岚
奕正卿
全飞珍
刘雅静
王香梅
冷小谷
梁丘菲菲
成书雁
延施诗
森俊弼
无孤菱
厉采柳
申屠尔阳
洪妙旋
江听枫
锁傲之
频紫文
才清秋
尤雪晴
檀虹雨
布雅安
贝承载
游碧琴
谷俊侠
謇和裕
暴喜悦
和睿哲
敖嘉年
许飞昂
祝安静
凤智晖
庄鸿福
濯曼蔓
载歌云
图门诗双
尉清舒
单安娜
阚浩邈
招雨旋
卫山槐
朴安白
谏语蕊
伯凌春
佴以松
莱夏菡
仲孙芸若
明海莹
庹涵蕾
潘白柏
祖翔飞
太叔星津
墨俊风
翦子真
侯悠柔
酆天恩
鱼乐蓉
老秀媚
瓮倩丽
种念雁
袁芙蓉
马佳冰蝶
左俊茂
邴景中
亥承教
弭笑卉
丹映雁
浮凌青
云醉蝶
龙美华
印平文
崔静姝
凌元彤
令夏萱
季奇邃
嵇良奥
藤桐华
答代天
谢阳波
殷婉秀
鄞文曜
连从云
厍绣文
象碧萱
景鸿骞
濮阳凌春
鲜于灵安
登莹洁
逢向南
杜浩然
禄振凯
吴灵凡
禚语海
堵智刚
绍婉柔
千思真
忻锐翰
刚香岚
焉新荣
薛访梦
屈敏叡
悉又晴
寿怀思
恽贝莉
检友桃
佛晓丝
巧余妍
舜寻桃
召恬静
羿访曼
柳海亦
生芷蓝
以素怀
冯雨竹
竺向真
束晶灵
雍新月
甲夏柳
富骊萍
姚寻桃
良宜修
滕霞辉
笪思聪
孟初柳
赵驰鸿
艾书兰
始骊婧
蓬子萱
栋念真
畅如风
轩辕青亦
冀欣愉
兴飞兰
籍慧心
靖优扬
树吉玉
卯鸿达
折天韵
於凝丹
友阳云
粘斯文
廉怜阳
牢小蕊
续逸明
及天佑
芒梓玥
鲜千凡
庾雁露
性含巧
能白梅
东郭曼文
钞子石
余建义
后芮佳
宗政访儿
菅梓莹
随滢滢
麴夏菡
党才艺
宝凌寒
哀子楠
尧清妍
田华容
回菊华
家水悦
仍妙音
本斯琪
汉越泽
林英华
乾冬莲
迟凝冬
廖代天
贡虹彩
邹凌晓
系高兴
银嘉月
司空笑旋
五银河
齐翰音
蓝茂典
函秀敏
凭暮雨
闻翰墨
丑秀艾
戎骊娟
邱悦怡
卓飞掣
符元魁
苟琇芳
伍淑雅
香晴丽
寸元凯
巫马光启
局婉丽
练之玉
纳喇宏茂
岳阳煦
麻嘉美
撒远航
泉韵流
童晴岚
万锐立
陆若兰
拓跋运馨
容从蕾
鄂驰皓
闽夏寒
鄢山彤
谈易梦
修初夏
贾运珧
诸德海
仙飞沉
郜半双
澄醉冬
声新之
母代秋
吕傲柔
尚幼菱
桓凝心
蒲幻桃
妫凝莲
卜碧玉
历同光
佟骏祥
闫蓉蓉
益绿蝶
狄晓旋
星天蓝
乌雅欣艳
台和蔼
山兰英
秋博厚
候盼雁
旁恺乐
权晓莉
淳于雪莲
杭和畅
疏怡宁
邸晗玥
禹骏年
元哲思
锺离森丽
段干芳苓
庆博实
易宏逸
寇初夏
皇香天
建怡嘉
方梦菲
伏思菱
朋新语
夹谷和玉
樊思美
潮梦秋
拜明明
帖司晨
霜凡儿
宣迎荷
奇梦玉
言雅丹
校格格
祢思淼
福安珊
区白易
萧新梅
弥沛珊
程滨海
公孙绣梓
圣白莲
居凝云
贰星然
彭白竹
经修伟
陈琳怡
虎振平
佟佳惜萍
宇盼盼
茹碧曼
杨琦巧
张季同
侨瑞灵
板宜然
盘绍祺
隗琪华
势平雅
席嘉珍
赫思云
春新美
亢德泽
偶绿蕊
窦梓暄
闭晓山
娄梓馨
彤婵娟
白偲偲
沈莹琇
恭骊艳
智秀逸
弘宇航
鹿新儿
肖甘雨
脱弘阔
鲁初蝶
东柳思
肥涵菡
戊思松
闻人觅珍
戴夜蓉
鞠珺俐
泥念烟
贵悦恺
韩灵秋
斯正诚
僪秀曼
钊星晴
陀浩邈
坚如意
闪逸春
赫连湛静
业安妮
乌旭尧
寒叶芳
于菀菀
豆英豪
覃洮洮
花蕙兰
泰闵雨
璩天元
盖甜恬
皇甫惜珊
栾高雅
源范明
孝听云
北问春
九辰韦
谯姝惠
书忆彤
海紫安
子车雁芙
貊勇男
秦平蓝
依幼珊
堂丽泽
桥英睿
钟离经亘
张廖青旋
宇文宛筠
章佳君豪
澹台珠轩
满彤云
郁语诗
世诗兰
帛建本
魏翠芙
都嘉纳
士元冬
双琳芳
是鸿波
不友琴
时凌寒
聂痴梅
宰韦柔
乐涵畅
释秋寒
荀清雅
扈运凯
资晴虹
线湘君
祭绮琴
从乐心
过安吉
路雁蓉
糜心香
百雪珊
华红艳
光诗蕊
贯平卉
司徒斯雅
仆灵槐
屠映萱
圭紫云
壬又青
玄蓓蕾
隐梦云
米初夏
所乐湛
况恬默
单于夜梦
烟海之
梅春竹
御之云
第鹏鹍
漆菡梅
孛振翱
巢初柔
孔闲静
实蕴美
罗觅儿
乔志专
京惜文
唐山晴
南门丽芳
左丘庄静
令狐善和
颛孙晓灵
吉韶敏
那含之
宓夜天
任丝柳
暨成仁
包学海
清振宇
斋文光
衡梦竹
向琴雪
呼天纵
丘琇莹
邗天骄
伊韶丽
保含雁
在忆敏
邰古兰
曾德容
宏梦菲
承飞文
终浩丽
夏飞驰
禾思义
秘秀媛
苑玉成
徐红雪
戈静婉
敏痴海
冼坚白
愚依秋
万俟德泽
颜建白
由兰芝
昂海融
独冰绿
顿映天
摩觅露
六嫣然
裴初曼
羽香天
上官依波
操幼晴
逮寄瑶
袭迎梅
枝艳卉
东方晗晗
洛晶晶
端木依楠
买刚洁
运弘新
昔惜儿
文晨璐
逄乐池
仵欣然
刑白风
析曼珍
果银柳
德夏瑶
真红旭
班英逸
酒昊苍
空云臻
潜依波
钮圣杰
苌齐敏
度友梅
歧盈秀
改晨风
农金枝
城乐然
邵香春
苗晶滢
涂曼珠
邶婷美
蛮雅洁
蒯念巧
针觅丹
钱香菱
毋芸芸
毓向薇
毛念雁
牧小蕊
韶念双
罕夏雪
理景辉
同建业
宦曼容
郑芝英
阴翠丝
似红豆
辟明亮
之傲南
威若雁
井惜玉
赧代芙
荤鸿畴
蒉君浩
范姜经纬
刁飞翮
胥文滨
后卓逸
茅静柏
楼瑛瑶
原玉兰
敬逸馨
衣亦竹
蒋丽珠
镇惜海
铁婷婷
干鸿煊
夏侯宜嘉
穰芳润
市雪卉
己新翰
微生芳润
仝和平
其向槐
繁芳洲
韦飞烟
慈思琳
督优乐
叶韵磬
委桂枫
缪清逸
接轩昂
归痴柏
将紫南
费莫梦凡
奉雅晗
戚元枫
佘醉波
辛红叶
让绿海
舒翰海
隋绿夏
隆起运
皮建树
闳夜梦
融涵韵
告鸿光
宋文茵
康秀洁
竹阳泽
年雁菱
诸葛曼吟
丛沈雅
掌雅美
集静枫
化谷蕊
敛芷荷
介若翠
蚁振海
斛星剑
温寄松
步俊名
施雅丽
义雨筠
利修为
劳修能
傅嘉美
稽尔竹
府良平
龚恨云
爱木兰
苏海瑶
表又蓝
么晶滢
穆含香
咸梦泽
却红香
崇阳秋
素叶丰
仲晨蓓
位晓燕
柴映寒
锐香卉
钦迎蓉
越白梅
通艳芳
字芬菲
漫翠巧
希辰龙
蔺晓蕾
员兰梦
董晴虹
捷博涉
叔琼岚
谬璇玑
驹华晖
法康时
完颜乐意
尔书兰
东门清卓
查娇洁
祈高卓
皋芳洲
纪映寒
蒙鸿轩
呼延温书
伦芷兰
汤开朗
司马奥婷
俎辰君
谭馨欣
矫秋灵
綦彭彭
甘寄琴
枚雅洁
礼晶晶
出问香
裔乐蕊
萨思宸
牛雪萍
桂寄春
吾小之
夙冷之
羊嘉音
湛朗宁
郏康成
陶暄嫣
柯水蕊
迮鸿运
楚雁风
熊俊雅
淡锐逸
公西温韦
百里代桃
闾丘子珍
巫婉丽
零安福
庞暄文
公麦冬
有玉龙
乘君昊
泣宜年
尹易梦
粟安筠
晁冰岚
大舒方
柔成益
考白梅
止明朗
旅珺娅
别建茗
哈灵秋
占海秋
相笑容
邓真茹
诗微婉
支寒雁
嬴雅宁
少博耘
狂清润
贲小凝
耿景行
桐文彦
丰玉轩
费新之
笃碧琳
谷梁秀越
宰父凝蝶
房静婉
雀燕舞
广采春
巩韦茹
古亦凝
荣心宜
缑云飞
应美如
黎旭东
道子蕙
冒谷之
甄若枫
羊舌学文
守浩渺
咎倩秀
衅水丹
钭安怡
天清涵
悟半雪
简听云
关雨兰
勾安双
溥文斌
冠向露
开雅达
宁涵涵
塞可可
犁向明
来智宸
雪春岚
聊雨晨
诺骊娜
英语柔
卢睿德
曲婉容
裘泽宇
进雅志
昌明俊
桑贞韵
鲍碧玉
塔宛亦
洋天和
苍安和
帅婉君
訾绍辉
习梦菡
马令锋
庚晓霜
泷春柔
芮星雨
项音悦
亓官天籁
安力勤
犹逸云
牟安莲
蔡方仪
琴靖荷
代成双
可俊杰
孙欣然
速孟夏
常方方
辉铃语
姓令璟
仇半凡
奚娴淑
尾傲丝
赛春冬
嘉友菱
卑元驹
硕波峻
宾新雨
冉问薇
刀建元
受雅云
褒恬悦
竭晨萱
仉晨涛
那拉霞英
节怜双
信夏真
力嘉懿
倪春海
蒿海菡
辜湘云
勇凝然
幸黎明
赏静涵
商津童
拱烨华
阎新洁
储安翔
骑志明
逯秋巧
李惜萱
养珍瑞
盍彦露
宫泽雨
祁绿旋
铎朝雨
贺伶俐
功哲妍
夫丹寒
求梦旋
禽尔容
水思凡
毕霞雰
司寇霓云
中长钰
饶千凡
机雨柏
巴作人
兆童彤
严宇寰
长孙春雪
佼宏盛
瞿英叡
飞兰蕙
虞绮玉
莘采波
阿锐阵
错清漪
松雨筠
汲向雁
长兰芳
示雪枫
门流如
杞清韵
漆雕昌茂
边子怡
邝思敏
慕清润
藏采薇
遇舒云
夕欣悦
营宛菡
殳乐蓉
富察依波
前小凝
詹乐正
侍智菱
钟晶瑶
允天悦
碧经赋
绪怡木
波问芙
甫梦月
章晴霞
公叔囡囡
战思雁
邬倚云
野芳懿
纳青柏
勤清逸
展贞芳
乐正问萍
乜绮云
风嘉淑
典珠佩
剑秀媛
沐千凝
怀冬梅
箕冬亦
俟语山
薄夏之
晋从蕾
琦嘉许
行娴雅
卷沛凝
赤幼霜
蹇芸馨
励鸿畅
石筠溪
戏格格
阙易蓉
太史初阳
充嘉玉
车子平
纵琰琬
库智美
亓阳飇
慕容兴贤
浑怜南
愈绮彤
黄若云
僧凡桃
汝淳静
定涵忍
巨靖之
翁静雅
官致萱
仰德润
褚鸿波
寻芸儿
汗流婉
骆琳溪
汪又槐
曹若淑
碧鲁华采
郝胤雅
植红云
次元容
姬如松
抗哲美
浦悦心
强春荷
休红豆
端孤兰
渠宵月
沙彭魄
范融雪
郸昊然
匡星辰
腾安歌
睢鸿祯
麦海之
奈初然
多玄雅
环笑晴
肇兴生
剧又青
计温茂
翠天韵
学康安
仪红叶
夷安志
律鸿运
金红旭
郦寄云
合桐欣
虢敏丽
喻春雪
公冶岚岚
莫书意
姜金鑫
紫代巧
靳彦慧
南宫雪珍
尉迟亦绿
锺雅彤
柏丹秋
闵丽华
睦雅爱
贸清华
永凝绿
弓惜雪
戢学真
解心远
濮靖之
但芷琪
滑叶农
国幼白
欧祺福
蹉奇伟
初元蝶
衷清馨
蔚星渊
栗康宁
蓟哲圣
赖痴春
郗寄波
姒新曦
周清懿
务嘉歆
旗笑天
镜千柔
沃兴昌
岑天禄
梁施然
申舒兰
邢忆辰
卞颖初
郭弘壮
邛开霁
管皎月
斐世英
望思美
封欣欣
达含桃
壤驷秋白
高曼蔓
欧阳忆枫
昝鸿风
徭悦宜
夔诗霜
翟凯歌
红嘉怡
顾和悦
藩灵枫
磨岚霏
池丹山
旷承业
类兰若
危语海
焦夜绿
盈尔风
公良慧晨
雷雅韵
宜良弼
葛弘方
霍高超
张简沙羽
军夏兰
慎平文
隽冰枫
西门凡之
潭诗珊
宛静枫
俞苇然
闾建华
善乐双
苦雪珊
郎寄蓝
喜运盛
宿之桃
阳欢悦
仁沛柔
玉桂华
南梓婷
何忆灵
臧寄灵
盛方方
伟北嘉
说骊英
公羊一雯
胡苑博
朱易绿
茆灵秀
问瑞云
师绮艳
阮德厚
茂欣怡
绳云泽
第五昆明
================================================
FILE: src/test/resource/teacher.txt
================================================
危兴修
陈继靖
盛家弘
史羡有
柯路炎
刘约舜
陶翰
丘雨夏
龚琅洋
陶杰祖
倪舒延
王望屏
周宇庆
邬孟鹏
廉容友
林豪银
林均峥
朱劝修
夏鹏勳
元凯霖
黎斯中
常建延
骆滔凌
林辩铿
孙赐超
胡钧文
席聚苞
邬先会
严曼拓
马览飞
陆汇祥
蔡楼汐
殷忠映
严甜琅
林当颜
赵子杜
赵淳滔
周敦弘
孙其相
童晖福
凌国窍
钱篱准
黄鹤盼
周豪灏
蔡葛固
谭皆佟
方升跋
刘余彤
虞舒冰
李峙发
孙琦科
蒲哥蜀
谭翀祥
范寒
庄闰
卫越相
邢律量
梁荡贯
田凛磊
霍超帅
沈晖和
成全珑
冯若康
戚千蔚
侯风有
徐管武
赖茗单
戚稠边
吴志裕
文秉时
陆栋衷
周任白
何禄达
饶庆
刘继笛
方尚杰
钟辽醒
洪配辰
甘华代
赖银
谢冶胜
洪栋颜
时腾朋
刘麦少
区秩新
夏绍
高炼巍
邓森滕
梁小爽
叶奋苏
罗跃厦
韩泰启
虞渭春
胡扬
骆鉴來
林舜锋
梁广业
欧燃轮
莫铮信
岑夕峪