spring-data-mongodb
1. mapping(定义Document)
所有的映射均由org.springframework.data.mongodb.core.convert.MappingMongoConverter类实现。
几点基准:
- 每个类均映射为一个mongodb中的Collection,Collection的名称使用驼峰式命名。
- 除@DbRef指定的属性之外,所有的属性均保存在该类中,包括嵌入在该类里的类。
1.1 _id字段的映射
@Id,@Field,id(属性名为id)均可用来指定_id。
|Field definition|Resulting Id-Fieldname in MongoDB|
|:—:|:—:|
|String id|_id|
|@Field String id|_id|
|@Field(“x”) String id|x|
|@Id String x|_id|
|@Field(“x”) @Id String x|_id|
|||
TODO 如果id不能转化为一个ObjectId怎么办?
1.2 映射的type对应
| Type | Type conversion | Sample |
|---|---|---|
| String | native | {“firstname” : “Dave”} |
double, Double, float, Float|native|{“weight” : 42.5}|
int, Integer, short, Short|native 32-bit integer|{“height” : 42}
long, Long|native 64-bit integer|{“height” : 42}|
Date, Timestamp|native|{“date” : ISODate(“2019-11-12T23:00:00.809Z”)}|
Array, List, BasicDBList|native|{“cookies” : [ … ]}
TODO test array?
1.3 注解(Mapping annotation overview)
@Id- applied at the field level to mark the field used for identity purpose.@Document- applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.@DBRef- applied at the field to indicate it is to be stored using a com.mongodb.DBRef.@Indexed- applied at the field level to describe how to index the field.@CompoundIndex- applied at the type level to declare Compound Indexes@GeoSpatialIndexed- applied at the field level to describe how to geoindex the field.@TextIndexed- applied at the field level to mark the field to be included in the text index.@Language- applied at the field level to set the language override property for text index.@Transient- by default all private fields are mapped to the document, this annotation excludes the field where it is applied from being stored in the database@PersistenceConstructor- marks a given constructor - even a package protected one - to use when instantiating the object from the database. Constructor arguments are mapped by name to the key values in the retrieved Document.@Value- this annotation is part of the Spring Framework . Within the mapping framework it can be applied to constructor arguments. This lets you use a Spring Expression Language statement to transform a key’s value retrieved in the database before it is used to construct a domain object. In order to reference a property of a given document one has to use expressions like:@Value("#root.myProperty")where root refers to the root of the given document.@Field- applied at the field level and described the name of the field as it will be represented in the MongoDB BSON document thus allowing the name to be different than the fieldname of the class.@Version- applied at field level is used for optimistic locking and checked for modification on save operations. The initial value is zero which is bumped automatically on every update.
记录的版本,示例
@TypeAlias("pers")在mongodb中该类的_class为pers。@PersistenceConstructor标记一个构造器,指定用来构造类的实例,并可以结合@Value使用,可以达到修改构造器用处。1
2
3
4
5
6
7
8
9
10
11
12
13
14@Document
static class ObjectContainer {
@Field("property") private final PrimitiveContainer m_property;
@PersistenceConstructor
public ObjectContainer(@Value("#root.property") PrimitiveContainer a_property) {
m_property = a_property;
}
public PrimitiveContainer property() {
return m_property;
}
}
2. 操作Mongodb
最常用的两个操作Mongodb的类是MongoTemple,Repository类。
2.1 连接Mongodb
使用MongoClient1
2
3public MongoClient mongoClient() {
return new MongoClient();
}
常用的MongoClient类构造方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public MongoClient(String host) {
this(new ServerAddress(host));
}
public MongoClient(String host, int port) {
this(new ServerAddress(host, port));
}
public MongoClient(ServerAddress addr) {
this(addr, (new Builder()).build());
}
public MongoClient(MongoClientURI uri) {
super(uri);
}
MongoClientFactoryBean对应MongoClient的工厂模式,可以用来构建MongoClient(createInstance方法)。
2.2 使用MongoTemple
MongoTemple的三种构造方法
MongoTemplate(MongoClient mongo, String databaseName)- takes the com.mongodb.MongoClient object and the default database name to operate against.MongoTemplate(MongoDbFactory mongoDbFactory)- takes a MongoDbFactory object that encapsulated the com.mongodb.MongoClient object, database name, and username and password.MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter)- adds a MongoConverter to use for mapping.
MongoTemple的CRUD:
插入数据:1
2
3
4
5
6
7
8
9void save (Object objectToSave) Save the object to the default collection.
void save (Object objectToSave, String collectionName) Save the object to the specified collection.
A similar set of insert operations is listed below
void insert (Object objectToSave) Insert the object to the default collection.
void insert (Object objectToSave, String collectionName) Insert the object to the specified collection.
区别:
insert在出现相同的id的时候,会出现错误,而save会覆盖原值。(只限于id)
1 | insertAll(Collection objectionsToSave) |
Update:1
2
3updateFirst Updates the first document that matches the query document criteria with the provided updated document.
updateMulti Updates all objects that match the query document criteria with the provided updated document.
常见的update方法的示例1
2WriteResult wr = mongoTemplate.updateMulti(new Query(where("accounts.accountType").is(Account.Type.SAVINGS)),
new Update().inc("accounts.$.balance", 50.00), Account.class);
Update的方法(和mongodb中的原生update方法类似):1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18[TODO to review]
Update addToSet (String key, Object value) Update using the $addToSet update modifier
Update currentDate (String key) Update using the $currentDate update modifier
Update currentTimestamp (String key) Update using the $currentDate update modifier with $type timestamp
Update inc (String key, Number inc) Update using the $inc update modifier
Update max (String key, Object max) Update using the $max update modifier
Update min (String key, Object min) Update using the $min update modifier
Update multiply (String key, Number multiplier) Update using the $mul update modifier
Update pop (String key, Update.Position pos) Update using the $pop update modifier
Update pull (String key, Object value) Update using the $pull update modifier
Update pullAll (String key, Object[] values) Update using the $pullAll update modifier
Update push (String key, Object value) Update using the $push update modifier
Update pushAll (String key, Object[] values) Update using the $pushAll update modifier
Update rename (String oldName, String newName) Update using the $rename update modifier
Update set (String key, Object value) Update using the $set update modifier
Update setOnInsert (String key, Object value) Update using the $setOnInsert update modifier
Update unset (String key) Update using the $unset update modifier
删除数据1
2
3
4
5
6
7
8
9
10
11template.remove(tywin, "GOT"); <1>
template.remove(query(where("lastname").is("lannister")), "GOT"); <2>
template.remove(new Query().limit(3), "GOT"); <3>
template.findAllAndRemove(query(where("lastname").is("lannister"), "GOT");<4>
template.findAllAndRemove(new Query().limit(3), "GOT"); <5>
Remove a single entity via its _id from the associated collection.
Remove all documents matching the criteria of the query from the GOT collection.
Remove the first 3 documents in the GOT collection. Unlike <2>, the documents to remove are identified via their _id executing the given query applying sort, limit and skip options first and then remove all at once in a separate step.
Remove all documents matching the criteria of the query from the GOT collection. Unlike <3>, documents do not get deleted in a batch but one by one.
Remove the first 3 documents in the GOT collection. Unlike <3>, documents do not get deleted in a batch but one by one.
区别:
remove当有多个需要删除的记录时,一次删除;而findAllAndRemove则是一跳一条记录删除。
Upsert数据
如果数据库中没有该记录则插入数据库中:1
template.upsert(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update")), update("address", addr), Person.class);
查找并修改数据:返回原值
1 | <T> T findAndModify(Query query, Update update, Class<T> entityClass); |
如果想返回新值:1
p = template.findAndModify(query, update, new FindAndModifyOptions().returnNew(true), Person.class);
The FindAndModifyOptions lets you set the options of returnNew, upsert, and remove.
查找数据:[TODO review]
BasicQuery用于直接处理mongo的查找语句。
1
2BasicQuery query = new BasicQuery("{ age : { $lt : 50 }, accounts.balance : { $gt : 1000.00 }}");
List<Person> result = mongoTemplate.find(query, Person.class);标准面向对象的Query方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Criteria all (Object o) Creates a criterion using the $all operator
Criteria and (String key) Adds a chained Criteria with the specified key to the current Criteria and returns the newly created one
Criteria andOperator (Criteria… criteria) Creates an and query using the $and operator for all of the provided criteria (requires MongoDB 2.0 or later)
Criteria elemMatch (Criteria c) Creates a criterion using the $elemMatch operator
Criteria exists (boolean b) Creates a criterion using the $exists operator
Criteria gt (Object o) Creates a criterion using the $gt operator
Criteria gte (Object o) Creates a criterion using the $gte operator
Criteria in (Object… o) Creates a criterion using the $in operator for a varargs argument.
Criteria in (Collection<?> collection) Creates a criterion using the $in operator using a collection
Criteria is (Object o) Creates a criterion using field matching ({ key:value }). If the specified value is a document, the order of the fields and exact equality in the document matters.
Criteria lt (Object o) Creates a criterion using the $lt operator
Criteria lte (Object o) Creates a criterion using the $lte operator
Criteria mod (Number value, Number remainder) Creates a criterion using the $mod operator
Criteria ne (Object o) Creates a criterion using the $ne operator
Criteria nin (Object… o) Creates a criterion using the $nin operator
Criteria norOperator (Criteria… criteria) Creates an nor query using the $nor operator for all of the provided criteria
Criteria not () Creates a criterion using the $not meta operator which affects the clause directly following
Criteria orOperator (Criteria… criteria) Creates an or query using the $or operator for all of the provided criteria
Criteria regex (String re) Creates a criterion using a $regex
Criteria size (int s) Creates a criterion using the $size operator
Criteria type (int t) Creates a criterion using the $type operator
1 | List<Person> result = mongoTemplate.find(query(where("age").lt(50) |
其他find的方法:
1
2
3
4
5`findAll` Query for a list of objects of type T from the collection.
`findOne` Map the results of an ad-hoc query on the collection to a single instance of an object of the specified type.
`findById` Return an object of the given id and target class.
`find` Map the results of an ad-hoc query on the collection to a List of the specified type.
`findAndRemove` Map the results of an ad-hoc query on the collection to a single instance of an object of the specified type. The first document that matches the query is returned and also removed from the collection in the database.TextQuery
1
2TextQuery.searching(new TextCriteria().matching("coffee").matching("-cake"));
TextQuery.searching(new TextCriteria().matching("coffee").notMatching("cake"));Query by Example(QBE)
TODO
2.3 使用Spring Data Repositories
Repositories只是作为一个Spring-data的一个标示,同时也是其的一个核心借口,内部不存在方法,所有的方法都是通过Spring的内部注入机制注入。
在Repositories上层是CrudRepository。CrudRepository借口定义了几个基本的方法。spring-data同时提供JpaRepository,MongoRepository接口,屏蔽了底层实现逻辑。
在CrudRepository上层是PagingAndSortingRepository,该接口定义了分页查询等接口。