SpringData Mongodb achieve the CRUD: MongoTemplate framework approach

SpringData Mongodb achieve the CRUD: MongoTemplate framework
MongoTemplate realize the connection between java code mongodb database, the site is safe.
MongoDB database collection MySQL database is equivalent to the equivalent table field equivalent column

A. Creating MongoTemplate instance.

1.java code创建

  1.1)数据库无密码:

      MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

      //"dbName":连接的数据库集合名称

      SimpleMongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient , "dbName"); 

      DbRefResolver dbRefResolver = new DefaultDbRefResolver(dbFactory);

      MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());

     converter.setTypeMapper(new DefaultMongoTypeMapper(null));

     //加入converter是去掉数据库文档中_class字段

     MongoTemplate template = new MongoTemplate(dbFactory, converter);

  1.2)数据库有密码验证

  UserCredentials userCredentials = new UserCredentials( "username", "password" );

  SimpleMongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient , "dbName",userCredentials );

             .....................(以下步骤同上).....................

Two .MongoTemplate of Crud operations mongodb database

 /* 约定 */

 /*object:新增的javaBean对象。collectionName:集合名称,相当于表名。*/

/*Collection<? extends Object> collection:批量操作时,对象的集合。例如List<User> collection*/

/*Query query = new Query()    query:条件*/

1.新增文档

 MongoTemplate提供了save()和insert()两种方式。

 save:新增文档时,如果有_id文档存在则修改,不存在则增加,相当于根据条件调用insert或update方法。

 insert:新增文档时,如果有_id文档存在则会新增失败,即不会修改之前的值,也不会重新增加。

 用法:

            template.save(object);

            template.save(object,collectionName);

           template.insert(object);

           template.insert(object,collectionName);

           //批量插入

           template.insertAll(collection);

           template.insert(collection,collectionName);

2. Delete the document

            template.remove(query,collectionName);

            template.dropCollection(collectionName);//删除集合,即该张表会被删除

3. Modify the document

           . updateFirst   只修改符合条件第一条数据

           . updateMulti  修改符合条件的所有所有

           . upsert          修改符合条件时如果不存在则会新增加一条数据,相当于执行了insert()方法

           /************ Update update=new Update() : update 需要更新的内容 *****************************/

update.set ( "key1", "value1 ") the set "key1" is a value corresponding to "value1", if there is no "key1" data, it will add a new message key1: VALUE1
update.inc ( "SUM" , 100) inc is cumulative calculation, i.e., plus sum based on the original 100, corresponding to 100 + sum sum =
update.multiply ( "sum", is calculated 100) multiplications, i.e. sum multiplied by the original base 100, corresponding to sum = 100 * SUM
update.rename ( "key2", "K2") is used to modify the rename the key, that "key2": "value2" changed to "K2": "value2"
update.unset ( "key3") delete key information "key3", that is, remove the key from the document
update.pull ( "array", "a1 ") to delete the array array of "a1". For example, "array": [ "a1" , "a2", "a3"], Result "a1" after "Array": [ "A2", "A3"]
update.pullAll ( "Array", Object [] values) can be deleted at a time within an array of multiple values
update.push ( "array", "a3 ") is added to the array array "a3" (does not check whether the repeated elements in the array), array "array" will not exist the new array. Results and modified "Array": [ "A2", "A3", "A3"]
update.pushAll ( "Array",
update.addToSet ( "array", "a3 ") is added to the array array "a3" (to check whether the elements in the array will be repeated), the array "array" does not exist in the array will be new. Results and modified "Array": [ "A2", "A3"]
update.pop ( "Array", Update.Position.FIRST) from the beginning of the array / end "array" (Update.Position.FIRST / Update.Position.LAST ) removes an element
/ **************************************************************** perform the update operation ************ ************************************************************ /

               //更新符合query条件的第一条数据

               template.updateFirst(query, update, collectionName);

               //更新符合query条件的所有数据

               template.updateMulti(query, update, collectionName);

              //更新符合条件时如果不存在则会新增加一条数据,相当于执行了insert()方法

               template. upsert(query, update, collectionName);

4.查询操作

/ ********************************************************** ready query ******************* ************************************************************ /

                      Query query=new Query();

                      Query query=new Query(CriteriaDefinition criteriaDefinition);

 !CriteriaDefinition是接口,Criteria是其实现类

/ **************************** query condition setting ****************** ************************************************************ /

Some commonly used methods Query
return type of the method described application example
Query addCriteria (Criteria criteria) is added to the query in query query.addCriteria (Criteria.where ( "name") IS ( "Jack").);
Query Skip (int Skip) the first index skip query data from the beginning, before the skip skip data subscript small scale from 0 query.skip (skip);
query limit (int limit) to limit the maximum number of return data query.limit (limit);
query withHint (String name) do forced index query with
query with (Sort sort) can be used for sorting
query.with (new Sort (Sort.Direction.DESC, " time"));

query.with(new Sort(Sort.Direction.ASC,“time”));

Query with (Pageable pageable) Pageable objects, there are skip, limit, sort information, so you can do paging and sorting
static Query query (Criteria criteria) Query.query (Criteria.where ( "name"). Is ( "jack")) ;
DBObject getQueryObject ()
field, fields ()
field, the specified field can be used to make queries query.fields () include ( "age" ) exclude ( "name")..;

It may also be used as a tool to return the specified field (behind example)

query.fields()

Criteria class common method of
static Criteria where (String key) to create a key, key key query.addCriteria That query (Criteria.where ( "name") IS ( "Jack").);
Static Criteria
byExample (Object Example)

() 

static Criteria
byExample(Example<?> example)

 ()

Criteria is (Object obj) is equal to (==) obj query.addCriteria (Criteria.where ( "name") IS ( "obj").);
Criteria and (String Key) and, a plurality of fields for queries simultaneously query ( . WHERE ( "key1") iS ( "VALUE1") and ( "key2") iS ( "value2"));..
Criteria NE (Object O) is not (not equal)
Query (WHERE ( "siteId"). ne (null)); // query siteId is not empty of data

query (where ( "name") ne ( "not that value")); //

Criteria lt(Object o) 小于(<)
query.addCriteria(Criteria.where(“insert_date”).gte(Date1).lte(Date2));

query.addCriteria(Criteria.where(“age”).gte(20).lte(30));

Criteria lte (Object o) less than or equal (<=)
Criteria gt (Object O) is greater than (>)
Criteria GTE (Object O) is greater than equal to (> =)
Criteria
in (Object ... CO.'S)

... in the inside (key corresponding to the data contained in the co li)
String [] STRs = ...;

query.addCriteria(Criteria.where(“name”).in((Object[]) strs));

或query.addCriteria(Criteria.where(“name”).in(obj1,obj2,obj3,…));

Criteria
in(Collection<?> co)

List collec=...;

query.addCriteria(Criteria.where(“key”).in(collec));

Criteria
nin(Object… o)

Not ... in (and in reverse) (slightly)
Criteria
nin (Collection <?> O)

Criteria mod (Number value, Number remainder )
modulo (remainder) operation, namely: key value corresponding% value == remainder (modulo is equal REMAINDER)

// {key:15} {key2:15}

query.addCriteria(Criteria.where(“key”).mod(10,3));

// key condition is not satisfied; key2 conditions are satisfied

Criteria
all(Object… col)

key corresponding to the key set comprising col (all containing relationship, in relation is included)
query.addCriteria (Criteria.where ( "key") All ( "N1", "N2").); // key corresponding to this time the value should be a set of

query.addCriteria(Criteria.where(“nameList”).all((Object[]) names)));

Criteria
all(Collection<?> col)

 List<Object> collec=...;

query.addCriteria(Criteria.where(“key”).all(collec));

Criteria
size(int s)

Matching elements of the set key corresponding to the specified number (!!! image can not be <5 such matching range)
// {key: [ "foo", "Lue", "CUA"]}

query.addCriteria(Criteria.where(“key”).size(3));

Criteria exists (boolean b) query field is present (true: there is, false: does not exist) query.addCriteria (. Criteria.where ( "confirmTime") EXISTS (false));
Criteria of the type (int t)
Criteria not () to take anti
// Note:. not () is () this is wrong, do not follow is not () back ()

query.addCriteria(Criteria.where(“number”).not().lte(2)); //number<=2取反,即number>2

Criteria regex (String re) Fuzzy queries (examples see below)
Criteria REGEX (Re String, String Options)
Options Optional values: i / m / x / s

// i represents a case insensitive

// m ^ and $ can be used like a regular expression to identify a database using \ start character and a character in each row n newline.

//x

// s If this modifier is set, meta-character dot pattern matches all characters, line breaks. Without this modifier, the dot does not match newline.

REGEX Criteria (the Pattern pattern)
the Pattern of Pattern.compile pattern = ( "regular expressions");

query.addCriteria(Criteria.where(“resourceName”).regex(pattern));

Criteria orOperator (Criteria ... criteria)
or more of a plurality of conditions Criteria (or) operation

(a || b)

Criteria c1=Criteria.where(“name”).is(“张三”));

Criteria c2=Criteria.where(“age”).is(25));

query.addCriteria(new Criteria().orOperator(c1, c2));

Criteria norOperator (Criteria ... criteria)
perform mongodb of $ nor operation, meaning:

$ Or return the document does not meet the conditions.

That return is not satisfied (a || b) documents

(Grammar with orOperator)
Criteria andOperator (Criteria Criteria ...)
and more conditions (and) operation

(a && b)

(With orOperator)
Criteria elemMatch (Criteria c)
the object in the array parameter query

"Users": [{ "name": "Joe Smith", "age": 20, "hobby": "internet"}, {}, ...]

Criteria cri=Criteria.where(“name”).is(“张三”));

query.addCriteria(Criteria.where(users).elemMatch(cri);

Criteria registerCriteriaChainElement(Criteria criteria)

Criteria alike(Example<?> sample)
Criteria withinSphere(Circle circle)
Criteria within(Shape shape)
Criteria near(Point point)
Criteria nearSphere(Point point)
Criteria intersects(GeoJson geoJson)
Criteria maxDistance(double maxDistance)
Criteria minDistance(double minDistance)

boolean lastOperatorWasNot()
Pattern toPattern(String regex, String options)
String getKey()
DBObject getCriteriaObject()
DBObject getSingleCriteriaObject()
BasicDBList createCriteriaList(Criteria[] criteria)
void setValue(DBObject dbo, String key, Object value)
boolean createNearCriteriaForCommand(String command, String operation, double maxDistance)
boolean simpleCriteriaEquals(Criteria left, Criteria right)
boolean isEqual(Object left, Object right)
int hashCode()
static boolean requiresGeoJsonFormat(Object value)
/** 利用regex做迷糊查询 **/

   private String regexFilter(String regex) {
         if (regex.equals("*")) {
               return "\\" + regex;
         } else {
             return regex;
         }
     }

  query.addCriteria(Criteria.where("name").regex(".*" + regexFilter("StringValue") + ".*"));

/****/

/ ********************************************************** page ******************** ********************* /

    方式一:   

         (单个字段排序)

        query.with(new Sort(Sort.Direction.DESC,"time"));

        query.with(new Sort(Sort.Direction.ASC,"time"));

          (多个字段同事排序)

         query.with(new Sort(Direction.ASC,"time1","time2","time3"));

          (不同字段不同排序)

         List<Sort.Order>orderList=new ArrayList<Sort.Order>();  

         orderList.add(new Sort.Order(Direction.ASC, "time1"));  

         orderList.add(new Sort.Order(Direction.DESC, "tim2"));  

         query.with(new Sort(orderList));  

          先按照time1升序,在按照time2降序

   方式二:

         int page=3;//第几页
         int size=30;//每页条数
         Sort sort=new Sort(Sort.Direction.ASC, "update_time");//排序,多条件排序同上
         Pageable pageable=new PageRequest(page, size, sort);
         query.with(pageable);

/ ********************************************************** sort ******************** ********************* /

 方式一:

   query.skip(skip);

   query.limit(limit);

 方式二:

    (同上—分页)

/ **************************** Returns the specified field ****************** ************************************************************ /

 利用 BasicQuery指定返回的字段

方式一:

 BasicDBObject queryObject=new BasicDBObject();

 BasicDBObject  fieldsObject=new BasicDBObject();//fieldsObject可以指定返回字段

 fieldsObject.put(key,val);

  //key:数据库的字段

  //val:1或true表示返回;0或false表示不返回。

  !注:_id默认是1,没指定返回该字段时,默认会返回,只有设置为0就不会返回该字段。

  Query query=new BasicQuery(queryObject, fieldsObject)

 方式二:(利用 Field 类)

 BasicDBObject queryObject=new BasicDBObject();

 Field  field = new Field();  

 field.exclude("key1");//不返回key1,等同于把 fieldsObject.put(key,val)的val设置为0.

 field.include("key2");//返回key2,等同于把 fieldsObject.put(key,val)的val设置为1.

 BasicDBObject  fieldsObject=field.getFieldsObject();

 Query query=new BasicQuery(queryObject, fieldsObject);

/ ********************************************************** execution template ******************* ************************************************************ /

 collectionName:数据库集合名,即表名。

 query:上面生成的条件。

 entityClass:返回的数据被映射成的类型。

Some common methods MongoTemplate provided crud
return Description methodName example
T findOne (Query query, Class entityClass , String collectionName) User user = template.findOne (query, User.class, "collectionName"); query returns a Data
List find ( query query, Class entityClass, String collectionName ) List users = template.find (query, User.class, "collectionName"); queries meet the conditions of all the
List findAll (Class entityClass, String collectionName ) List users = template.findAll (User. class, "collectionName"); to query the data tables all
List
findAllAndRemove (query query, class entityClass, String

collectionName)

T findAndRemove(Query query, Class entityClass, String collectionName)
T findAndModify(Query query, Update update, Class entityClass, String collectionName)
T findById(Object id, Class entityClass, String collectionName)

         插入(新增)相关方法	 

void save(Object objectToSave, String collectionName)
User user=…;

template.save(user, “collectionName”);

void insert(Object objectToSave, String collectionName) template.insert(user, “collectionName”); 存入单个对象
void insert(Collection<? extends Object> batchToSave, String collectionName)
List users=…;

template.insert(users, “collectionName”);

It can be stored in a collection of objects

      删除相关方法

void dropCollection(String collectionName) 该张表全部数据会被删除
WriteResult remove(Query query, String collectionName) template.remove(query, “collectionName”);
WriteResult remove(Query query, Class<?> entityClass, String collectionName)

    修改文档相关方法

WriteResult updateFirst (Query query, Update update , String collectionName) template.updateFirst (query, update, "collectionName"); // update first query data in line with the conditions of
<?> WriteResult updateFirst (Query query , Update update, Class entityClass , String collectionName)
WriteResult updateMulti (Query query, update update, String collectionName) template.updateMulti (query, update, "collectionName"); // update query data that meets all the conditions of
WriteResult updateMulti (Query query, update update , Class <? > entityClass, String collectionName)
WriteResult upsert (Query Query, update update, String collectionName) Template upsert (Query, update, collectionName);. when the update // If there is no qualifying will add a new data, equivalent to the implementation of the insert () method
WriteResult upsert (Query query, Update update , Class <?> entityClass, String collectionName)

   统计数据数量

long count(Query query, String collectionName)

 查询是否存在

boolean exists(Query query, String collectionName)

/ ** packets, aggregate queries Group ** /

Method a: Method using a group of class DBCollection.

   方法:1.DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce);

           2.DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce, String finalize);

           3.DBObject group(DBObject key, DBObject cond, DBObject initial, String reduce, String finalize, ReadPreference readPreference)

key: specify one or more documents fields are grouped. And both keyf must have a
keyf: accept a javascript function. Field to determine the dynamic packet document. And must have both a key
initial: reduce the variables used in the initialization, the initialization document polymerization results.
reduce: reduce function to execute. Function needs to return a value.
cond: condition to perform filtering.
finallize: reduce the execution is completed, the final result set returned function before executing the result set. Alternatively
DBCollection dbc = template.getCollection ( "collectionName" );

String reduce = "function(doc,prev){\n" +
                      " prev.count+=1; \n" +
                      " }";

DBObject  key=new BasicDBObject("state",1);

DBObject cond=query.getQueryObject();

DBObject initial=new BasicDBObject("count",0);

DBObject result = dbc.group(key, cond, initial, reduce);

Map map = result.toMap();

for (Map.Entry o : map.entrySet()) {

    System.out.println(o.getKey() + " " + o.getValue());

}

Method two: aggregate polymerization

  方法:aggregate(Aggregation aggregation, String collectionName, Class<O> outputType);

Aggregation keyword Aggregation:
TypedAggregation aggregation keyword <?>
Class outputType: output type, you can specify a particular entity type.
String inputCollectionName :.
Class inputType <?>: An input type, which is a collection of operation.
String collectionName:

 !注:Aggregation 提供了一系列mongoDB的操作方法,比如match,unwind,limit...等等。

  Criteria criteria = where("...").....

 AggregationOperation match = new MatchOperation(criteria);

  

 UnwindOperation unwind = new UnwindOperation(Fields.field("values"));

 SortOperation sort = new SortOperation(new Sort("..."));



AggregationOperation group = new GroupOperation(Fields.fields("deviceId")).first("deviceId").as("deviceId").count().as("value");

AggregationOperation projection = new ProjectionOperation(fields(“events”)).and("_id").as(“deviceId”).andExclude("_id");

 Aggregation aggregation = Aggregation.newAggregation(match, unwind, sort, group, projection);

 AggregationResults<User> aggRes = mongoTemplate.aggregate(aggregation, "collectionName", User.class);

 List<User> listUser = aggRes.getMappedResults();

(一般可用 BasicDBObject 这个类接受,而不用User)

Guess you like

Origin blog.csdn.net/linjpg/article/details/88568844