前言:在上一篇文章中(PS:https://www.zifangsky.cn/923.html)我简单介绍了如何在Linux中安装MongoDB以及MongoDB的增删改查等基本命令用法(PS:更多MongoDB命令可以参考

一 使用MongoDB JDBC 驱动操作MongoDB

(1)下载mongo-java-driver驱动:

下载之后向项目中引入 mongo-java-driver-3.4.2.jar 这个jar包即可

(2)创建JDBC连接:

对于MongoDB来说,默认安装的MongoDB是不带安全认证的。但是为了提高MongoDB的安全性,我们通常需要添加上密码认证。这两种方式获取JDBC连接的示例代码如下:

Java

package cn.zifangsky.test.mongodb;

import java.util.Arrays;

import org.bson.Document;

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoDatabase;

public class MongoDBJDBC {

private static final String SERVER = "192.168.1.159"; //安装MongoDB的服务器IP

private static final int PORT = 27000; //MongoDB服务端口

private static final String USERNAME = "appuser"; //认证用户名

private static final String PASSWORD = "123456"; //认证密码

private static final String DATABASENAME = "zifangsky"; //指定数据库

/**

* 获取不带密码认证的MongoDatabase

* @return

*/

public static MongoDatabase getDatabaseNotAuth(){

MongoDatabase mongoDatabase = null;

try {

mongoDatabase = new MongoClient(SERVER, PORT).getDatabase(DATABASENAME);

} catch (Exception e) {

System.err.println( e.getClass().getName() + ": " + e.getMessage() );

}

return mongoDatabase;

}

/**

* 获取带密码认证的MongoDatabase

* @param username 认证用户

* @param databaseName 数据库

* @param passwd 密码

* @return MongoClient

*/

public static MongoDatabase getDatabaseWithAuth(){

MongoDatabase mongoDatabase = null;

try {

MongoCredential credential = MongoCredential.createScramSha1Credential(USERNAME, DATABASENAME, PASSWORD.toCharArray());

mongoDatabase = new MongoClient(new ServerAddress(SERVER, PORT),Arrays.asList(credential)).getDatabase(DATABASENAME);

} catch (Exception e) {

System.err.println( e.getClass().getName() + ": " + e.getMessage() );

}

return mongoDatabase;

}

/**

* 返回指定数据库的某个collection

* @param collection

* @return

*/

public static MongoCollection getCollection(String collection){

MongoDatabase mongoDatabase = getDatabaseWithAuth();

return mongoDatabase.getCollection(collection);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66packagecn.zifangsky.test.mongodb;

importjava.util.Arrays;

importorg.bson.Document;

importcom.mongodb.MongoClient;

importcom.mongodb.MongoCredential;

importcom.mongodb.ServerAddress;

importcom.mongodb.client.MongoCollection;

importcom.mongodb.client.MongoDatabase;

publicclassMongoDBJDBC{

privatestaticfinalStringSERVER="192.168.1.159";//安装MongoDB的服务器IP

privatestaticfinalintPORT=27000;//MongoDB服务端口

privatestaticfinalStringUSERNAME="appuser";//认证用户名

privatestaticfinalStringPASSWORD="123456";//认证密码

privatestaticfinalStringDATABASENAME="zifangsky";//指定数据库

/**

* 获取不带密码认证的MongoDatabase

* @return

*/

publicstaticMongoDatabasegetDatabaseNotAuth(){

MongoDatabasemongoDatabase=null;

try{

mongoDatabase=newMongoClient(SERVER,PORT).getDatabase(DATABASENAME);

}catch(Exceptione){

System.err.println(e.getClass().getName()+": "+e.getMessage());

}

returnmongoDatabase;

}

/**

* 获取带密码认证的MongoDatabase

* @param username 认证用户

* @param databaseName 数据库

* @param passwd 密码

* @return MongoClient

*/

publicstaticMongoDatabasegetDatabaseWithAuth(){

MongoDatabasemongoDatabase=null;

try{

MongoCredentialcredential=MongoCredential.createScramSha1Credential(USERNAME,DATABASENAME,PASSWORD.toCharArray());

mongoDatabase=newMongoClient(newServerAddress(SERVER,PORT),Arrays.asList(credential)).getDatabase(DATABASENAME);

}catch(Exceptione){

System.err.println(e.getClass().getName()+": "+e.getMessage());

}

returnmongoDatabase;

}

/**

* 返回指定数据库的某个collection

* @param collection

* @return

*/

publicstaticMongoCollectiongetCollection(Stringcollection){

MongoDatabasemongoDatabase=getDatabaseWithAuth();

returnmongoDatabase.getCollection(collection);

}

}

注:关于第45行选择的加密方式”SCRAM-SHA-1″,这个是可以在MongoDB里的用户详情看到的,具体步骤如下:

(3)基本的增删改查示例:

Java

package cn.zifangsky.test.mongodb;

import java.util.ArrayList;

import java.util.List;

import org.bson.Document;

import org.junit.Test;

import com.mongodb.client.FindIterable;

import com.mongodb.client.MongoCollection;

import com.mongodb.client.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.model.Filters;

public class TestMongoDB {

/**

* 创建collection

*/

@Test

public void createCollection(){

MongoDatabase mongoDatabase = MongoDBJDBC.getDatabaseWithAuth();

mongoDatabase.createCollection("test1");

System.out.println("创建集合成功");

}

/**

* 获取一个collection,并插入数据

*/

@Test

public void insertCollection(){

//获取一个文档

MongoCollection collection = MongoDBJDBC.getCollection("test1");

/**

* 插入数据

*/

Document document1 = new Document("title","zifangsky的个人博客")

.append("author", "zifangsky")

.append("url", "https://www.zifangsky.cn/");

Document document2 = new Document("title","This's title")

.append("author", "zifangsky")

.append("url", "");

Document document3 = new Document("title","This's title2")

.append("author", "admin")

.append("url", "");

List documents = new ArrayList<>();

documents.add(document1);

documents.add(document2);

documents.add(document3);

collection.insertMany(documents);

System.out.println("文档插入成功");

System.out.println("count: " + collection.count());

}

/**

* 遍历一个collection

*/

@Test

public void iteratorCollection(){

MongoCollection collection = MongoDBJDBC.getCollection("test1");

FindIterable findIterable = collection.find();

MongoCursor mongoCursor = findIterable.iterator();

while (mongoCursor.hasNext()) {

Document doc = mongoCursor.next();

System.out.println(doc);

}

}

/**

* 替换collection中的某条数据

*/

@Test

public void updateData(){

MongoCollection collection = MongoDBJDBC.getCollection("test1");

collection.updateMany(Filters.eq("author", "zifangsky"), new Document("$set", new Document("title","测试")));

}

/**

* 删除collection中的某些数据

*/

@Test

public void deleteData(){

MongoCollection collection = MongoDBJDBC.getCollection("test1");

//删除符合条件的第一个文档

//collection.deleteOne(Filters.eq("author","zifangsky"));

//删除所有符合条件的文档

collection.deleteMany(Filters.eq("author","zifangsky"));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105packagecn.zifangsky.test.mongodb;

importjava.util.ArrayList;

importjava.util.List;

importorg.bson.Document;

importorg.junit.Test;

importcom.mongodb.client.FindIterable;

importcom.mongodb.client.MongoCollection;

importcom.mongodb.client.MongoCursor;

importcom.mongodb.client.MongoDatabase;

importcom.mongodb.client.model.Filters;

publicclassTestMongoDB{

/**

* 创建collection

*/

@Test

publicvoidcreateCollection(){

MongoDatabasemongoDatabase=MongoDBJDBC.getDatabaseWithAuth();

mongoDatabase.createCollection("test1");

System.out.println("创建集合成功");

}

/**

* 获取一个collection,并插入数据

*/

@Test

publicvoidinsertCollection(){

//获取一个文档

MongoCollectioncollection=MongoDBJDBC.getCollection("test1");

/**

* 插入数据

*/

Documentdocument1=newDocument("title","zifangsky的个人博客")

.append("author","zifangsky")

.append("url","https://www.zifangsky.cn/");

Documentdocument2=newDocument("title","This's title")

.append("author","zifangsky")

.append("url","");

Documentdocument3=newDocument("title","This's title2")

.append("author","admin")

.append("url","");

Listdocuments=newArrayList<>();

documents.add(document1);

documents.add(document2);

documents.add(document3);

collection.insertMany(documents);

System.out.println("文档插入成功");

System.out.println("count: "+collection.count());

}

/**

* 遍历一个collection

*/

@Test

publicvoiditeratorCollection(){

MongoCollectioncollection=MongoDBJDBC.getCollection("test1");

FindIterablefindIterable=collection.find();

MongoCursormongoCursor=findIterable.iterator();

while(mongoCursor.hasNext()){

Documentdoc=mongoCursor.next();

System.out.println(doc);

}

}

/**

* 替换collection中的某条数据

*/

@Test

publicvoidupdateData(){

MongoCollectioncollection=MongoDBJDBC.getCollection("test1");

collection.updateMany(Filters.eq("author","zifangsky"),newDocument("$set",newDocument("title","测试")));

}

/**

* 删除collection中的某些数据

*/

@Test

publicvoiddeleteData(){

MongoCollectioncollection=MongoDBJDBC.getCollection("test1");

//删除符合条件的第一个文档

//        collection.deleteOne(Filters.eq("author","zifangsky"));

//删除所有符合条件的文档

collection.deleteMany(Filters.eq("author","zifangsky"));

}

}

二 使用 Spring Data MongoDB 驱动操作MongoDB

Spring Data MongoDB属于Spring Data大家庭中的一员(PS:其他的还有Spring Data Redis、Spring Data JPA、Spring Data Neo4j等等),提供了在Spring应用中通过简单配置从而访问MongoDB的途径

其jar包可以从maven仓库下载,或者直接使用maven配置接口。参考下载地址如下:

(1)创建Spring Data MongoDB配置文件:

在这里我使用JavaConfig的方式来配置Spring Data MongoDB,,为了使代码更加简洁,我们通常需要继承AbstractMongoConfiguration这个类,其示例代码如下:

Java

package cn.zifangsky.config;

import java.util.Arrays;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;

import com.mongodb.MongoClient;

import com.mongodb.MongoCredential;

import com.mongodb.ServerAddress;

@Configuration

@EnableMongoRepositories(basePackages={"cn.zifangsky.model.mongodb","cn.zifangsky.mapper.mongodb"},repositoryImplementationPostfix="Impl")

public class MongoConfig extends AbstractMongoConfiguration{

@Override

protected String getDatabaseName() {

return "City";

}

@Override

public Mongo mongo() throws Exception {

MongoClient mongoClient = null;

try {

MongoCredential credential = MongoCredential.createScramSha1Credential("appuser", "City", "123456".toCharArray());

mongoClient = new MongoClient(new ServerAddress("192.168.1.159", 27000),Arrays.asList(credential));

} catch (Exception e) {

System.err.println( e.getClass().getName() + ": " + e.getMessage() );

}

return mongoClient;

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37packagecn.zifangsky.config;

importjava.util.Arrays;

importorg.springframework.context.annotation.Configuration;

importorg.springframework.data.mongodb.config.AbstractMongoConfiguration;

importorg.springframework.data.mongodb.repository.config.EnableMongoRepositories;

importcom.mongodb.Mongo;

importcom.mongodb.MongoClient;

importcom.mongodb.MongoCredential;

importcom.mongodb.ServerAddress;

@Configuration

@EnableMongoRepositories(basePackages={"cn.zifangsky.model.mongodb","cn.zifangsky.mapper.mongodb"},repositoryImplementationPostfix="Impl")

publicclassMongoConfigextendsAbstractMongoConfiguration{

@Override

protectedStringgetDatabaseName(){

return"City";

}

@Override

publicMongomongo()throwsException{

MongoClientmongoClient=null;

try{

MongoCredentialcredential=MongoCredential.createScramSha1Credential("appuser","City","123456".toCharArray());

mongoClient=newMongoClient(newServerAddress("192.168.1.159",27000),Arrays.asList(credential));

}catch(Exceptione){

System.err.println(e.getClass().getName()+": "+e.getMessage());

}

returnmongoClient;

}

}

从上面代码可以看出,这里获取MongoClient的方式跟普通的MongoDB JDBC获取MongoClient的方式类似,同时这里指定了使用的数据库名称为“City”

(2)为model类添加注解,实现MongoDB持久化:

Spring Data MongoDB 实现了对象文档之间的映射,其常用注解如下:注解描述@Document

@Id标注一个属性为该Collection的主键。在MongoDB中数据的主键通常为自动生成的复杂字符串,不需要我们手动设置

@Field设置某个属性对应于collection中自定义的字段,不手动添加该注解时MongoDB中的数据字段跟model的属性名一一对应

@DBRef标注某个属性引用其他的文档,这个文档有可能位于其他数据库中

@Version标注某个属性用作版本域

示例代码如下:

Java

package cn.zifangsky.model.mongodb;

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.mapping.Document;

import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection="province")

public class WeatherProvince {

@Id

private String id;

private String code;

@Field("country_id")

private Long countryId;

private String name;

private String description;

public WeatherProvince() {

}

public WeatherProvince(String code, Long countryId, String name, String description) {

this.code = code;

this.countryId = countryId;

this.name = name;

this.description = description;

}

public WeatherProvince(String id, String code, Long countryId, String name, String description) {

this.id = id;

this.code = code;

this.countryId = countryId;

this.name = name;

this.description = description;

}

//setter、getter方法略

@Override

public String toString() {

return "WeatherProvince [id=" + id + ", code=" + code + ", countryId=" + countryId + ", name=" + name

+ ", description=" + description + "]";

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48packagecn.zifangsky.model.mongodb;

importorg.springframework.data.annotation.Id;

importorg.springframework.data.mongodb.core.mapping.Document;

importorg.springframework.data.mongodb.core.mapping.Field;

@Document(collection="province")

publicclassWeatherProvince{

@Id

privateStringid;

privateStringcode;

@Field("country_id")

privateLongcountryId;

privateStringname;

privateStringdescription;

publicWeatherProvince(){

}

publicWeatherProvince(Stringcode,LongcountryId,Stringname,Stringdescription){

this.code=code;

this.countryId=countryId;

this.name=name;

this.description=description;

}

publicWeatherProvince(Stringid,Stringcode,LongcountryId,Stringname,Stringdescription){

this.id=id;

this.code=code;

this.countryId=countryId;

this.name=name;

this.description=description;

}

//setter、getter方法略

@Override

publicStringtoString(){

return"WeatherProvince [id="+id+", code="+code+", countryId="+countryId+", name="+name

+", description="+description+"]";

}

}

Java

package cn.zifangsky.model.mongodb;

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection="country")

public class WeatherCountry {

@Id

private String id;

private String code;

private String name;

private String description;

public WeatherCountry() {

}

public WeatherCountry(String code, String name, String description) {

this.code = code;

this.name = name;

this.description = description;

}

//setter、getter方法略

@Override

public String toString() {

return "WeatherCountry [id=" + id + ", code=" + code + ", name=" + name + ", description=" + description + "]";

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34packagecn.zifangsky.model.mongodb;

importorg.springframework.data.annotation.Id;

importorg.springframework.data.mongodb.core.mapping.Document;

@Document(collection="country")

publicclassWeatherCountry{

@Id

privateStringid;

privateStringcode;

privateStringname;

privateStringdescription;

publicWeatherCountry(){

}

publicWeatherCountry(Stringcode,Stringname,Stringdescription){

this.code=code;

this.name=name;

this.description=description;

}

//setter、getter方法略

@Override

publicStringtoString(){

return"WeatherCountry [id="+id+", code="+code+", name="+name+", description="+description+"]";

}

}

对于一个model类,如果它包含的其他实体不需要持久化为MongoDB文档,[email protected]示例如下:

i)Animal.java:

Java

package cn.zifangsky.model.mongodb;

public class Animal {

private String name;

private int age;

public Animal() {

}

public Animal(String name, int age) {

this.name = name;

this.age = age;

}

//setter、getter方法略

@Override

public String toString() {

return "Animal [name=" + name + ", age=" + age + "]";

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24packagecn.zifangsky.model.mongodb;

publicclassAnimal{

privateStringname;

privateintage;

publicAnimal(){

}

publicAnimal(Stringname,intage){

this.name=name;

this.age=age;

}

//setter、getter方法略

@Override

publicStringtoString(){

return"Animal [name="+name+", age="+age+"]";

}

}

ii)User.java:

Java

package cn.zifangsky.model.mongodb;

import java.util.List;

import org.springframework.data.annotation.Id;

import org.springframework.data.mongodb.core.mapping.Document;

@Document

public class User {

@Id

private String id;

private String name;

private String sex;

private int age;

private String contact;

private List ownPet;

public User() {

}

public User(String name, String sex, int age, String contact,

List ownPet) {

this.name = name;

this.sex = sex;

this.age = age;

this.contact = contact;

this.ownPet = ownPet;

}

//setter、getter方法略

@Override

public String toString() {

return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", contact=" + contact

+ ", ownPet=" + ownPet + "]";

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41packagecn.zifangsky.model.mongodb;

importjava.util.List;

importorg.springframework.data.annotation.Id;

importorg.springframework.data.mongodb.core.mapping.Document;

@Document

publicclassUser{

@Id

privateStringid;

privateStringname;

privateStringsex;

privateintage;

privateStringcontact;

privateListownPet;

publicUser(){

}

publicUser(Stringname,Stringsex,intage,Stringcontact,

ListownPet){

this.name=name;

this.sex=sex;

this.age=age;

this.contact=contact;

this.ownPet=ownPet;

}

//setter、getter方法略

@Override

publicStringtoString(){

return"User [id="+id+", name="+name+", sex="+sex+", age="+age+", contact="+contact

+", ownPet="+ownPet+"]";

}

}

在上面代码中,Animal类作为User类的其中一个属性,[email protected]

(3)使用MongoOperations访问MongoDB:

在前面我们通过继承AbstractMongoConfiguration的方式来配置MongoDB,MongoTemplate就已经被隐式地配置好了。因此接下来只需要在使用时注入MongoOperations即可访问MongoDB:

Java

package cn.zifangsky.test.mongodb;

import java.util.ArrayList;

import java.util.List;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.mongodb.core.MongoOperations;

import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;

import org.springframework.data.mongodb.core.query.Update;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mongodb.WriteResult;

import cn.zifangsky.model.mongodb.Animal;

import cn.zifangsky.model.mongodb.User;

import cn.zifangsky.model.mongodb.WeatherProvince;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:/context/context.xml"})

public class TestSpringDataMongoDB {

@Autowired

private MongoOperations mOperations;

@Test

public void testGetCount(){

Long count = mOperations.getCollection("country").count();

System.out.println(count);

}

@Test

public void testFind(){

List provinces = mOperations.find(Query.query(

Criteria.where("name").is("广西").and("country_id").is(1)), WeatherProvince.class,"province");

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

@Test

public void testRemove(){

WriteResult result = mOperations.remove(Query.query(Criteria.where("name").is("广西")), "province");

System.out.println(result.getN());

}

@Test

public void testSave(){

WeatherProvince province = new WeatherProvince("10131", 2l, "广西", "--");

mOperations.save(province, "province");

//*******************

User u = new User();

u.setName("zifangsky");

u.setAge(10);

Animal dog = new Animal("AlphaGo", 5);

Animal cat = new Animal("Black Cat", 2);

List pets = new ArrayList();

pets.add(dog);

pets.add(cat);

u.setOwnPet(pets);

//mOperations.save(u);

}

@Test

public void testUpdate(){

WriteResult result = mOperations.updateMulti(Query.query(Criteria.where("code").is("10130")), Update.update("description", "--"), "province");

System.out.println(result.getN());

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80packagecn.zifangsky.test.mongodb;

importjava.util.ArrayList;

importjava.util.List;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.data.mongodb.core.MongoOperations;

importorg.springframework.data.mongodb.core.query.Criteria;

importorg.springframework.data.mongodb.core.query.Query;

importorg.springframework.data.mongodb.core.query.Update;

importorg.springframework.test.context.ContextConfiguration;

importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

importcom.mongodb.WriteResult;

importcn.zifangsky.model.mongodb.Animal;

importcn.zifangsky.model.mongodb.User;

importcn.zifangsky.model.mongodb.WeatherProvince;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:/context/context.xml"})

publicclassTestSpringDataMongoDB{

@Autowired

privateMongoOperationsmOperations;

@Test

publicvoidtestGetCount(){

Longcount=mOperations.getCollection("country").count();

System.out.println(count);

}

@Test

publicvoidtestFind(){

Listprovinces=mOperations.find(Query.query(

Criteria.where("name").is("广西").and("country_id").is(1)),WeatherProvince.class,"province");

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

@Test

publicvoidtestRemove(){

WriteResultresult=mOperations.remove(Query.query(Criteria.where("name").is("广西")),"province");

System.out.println(result.getN());

}

@Test

publicvoidtestSave(){

WeatherProvinceprovince=newWeatherProvince("10131",2l,"广西","--");

mOperations.save(province,"province");

//*******************

Useru=newUser();

u.setName("zifangsky");

u.setAge(10);

Animaldog=newAnimal("AlphaGo",5);

Animalcat=newAnimal("Black Cat",2);

Listpets=newArrayList();

pets.add(dog);

pets.add(cat);

u.setOwnPet(pets);

//        mOperations.save(u);

}

@Test

publicvoidtestUpdate(){

WriteResultresult=mOperations.updateMulti(Query.query(Criteria.where("code").is("10130")),Update.update("description","--"),"province");

System.out.println(result.getN());

}

}

注:我这里仅仅只是列举了一些增删改查的基本用法,更多用法可以自行参考官方文档

(4)使用MongoDB Repository进一步简化访问MongoDB 的代码:

在上面的代码中,我们为了对MongoDB进行基本的操作,仍然需要自己手动写不少的查询、修改语句。其实MongoRepository这个Repository接口已经预先定义了基本的CRUD操作,因此我们只需要扩展该接口就可以进一步简化我们的代码了:

i)使用MongoRepository默认实现的方法:

Java

package cn.zifangsky.mapper.mongodb;

import org.springframework.data.mongodb.repository.MongoRepository;

import cn.zifangsky.mapper.mongodb.ProvinceOperations;

import cn.zifangsky.model.mongodb.WeatherProvince;

public interface ProvinceRepository extends MongoRepository{

}

1

2

3

4

5

6

7

8

9

10

11packagecn.zifangsky.mapper.mongodb;

importorg.springframework.data.mongodb.repository.MongoRepository;

importcn.zifangsky.mapper.mongodb.ProvinceOperations;

importcn.zifangsky.model.mongodb.WeatherProvince;

publicinterfaceProvinceRepositoryextendsMongoRepository{

}

在上面的代码中,我们除了继承了MongoRepository接口,并没有额外添加其他的方法。需要注意的是MongoRepository这里的S表示对应的实体类,而T则表示主键ID的类型

通过继承继承MongoRepository接口,我们不需要添加其他代码就可以使用计数、插入、遍历、删除、分页查询等方法了。示例代码如下:

Java

package cn.zifangsky.test.mongodb;

import java.util.Date;

import java.util.List;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;

import org.springframework.data.domain.PageRequest;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import cn.zifangsky.mapper.mongodb.ProvinceRepository;

import cn.zifangsky.model.mongodb.WeatherProvince;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:/context/context.xml"})

public class TestMongoRepository {

@Autowired

private ProvinceRepository provinceRepository;

/**

* 统计数据条数

*/

@Test

public void testGetCount(){

Long count = provinceRepository.count();

System.out.println(count);

}

/**

* 插入

*/

@Test

public void saveData(){

WeatherProvince province = new WeatherProvince("10121", 1l, "浙江", new Date().toString());

WeatherProvince result = provinceRepository.save(province);

System.out.println(result);

}

/**

* 查询所有

*/

@Test

public void testFindAll(){

List provinces = provinceRepository.findAll();

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

/**

* 分页查询

*/

@Test

public void testFindByPage(){

PageRequest pageRequest = new PageRequest(0, 5);

Page pages = provinceRepository.findAll(pageRequest);

List provinces = pages.getContent();

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75packagecn.zifangsky.test.mongodb;

importjava.util.Date;

importjava.util.List;

importorg.junit.Test;

importorg.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.data.domain.Page;

importorg.springframework.data.domain.PageRequest;

importorg.springframework.test.context.ContextConfiguration;

importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

importcn.zifangsky.mapper.mongodb.ProvinceRepository;

importcn.zifangsky.model.mongodb.WeatherProvince;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations={"classpath:/context/context.xml"})

publicclassTestMongoRepository{

@Autowired

privateProvinceRepositoryprovinceRepository;

/**

* 统计数据条数

*/

@Test

publicvoidtestGetCount(){

Longcount=provinceRepository.count();

System.out.println(count);

}

/**

* 插入

*/

@Test

publicvoidsaveData(){

WeatherProvinceprovince=newWeatherProvince("10121",1l,"浙江",newDate().toString());

WeatherProvinceresult=provinceRepository.save(province);

System.out.println(result);

}

/**

* 查询所有

*/

@Test

publicvoidtestFindAll(){

Listprovinces=provinceRepository.findAll();

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

/**

* 分页查询

*/

@Test

publicvoidtestFindByPage(){

PageRequestpageRequest=newPageRequest(0,5);

Pagepages=provinceRepository.findAll(pageRequest);

Listprovinces=pages.getContent();

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

}

最后的分页查询结果如下:

WeatherProvince [id=58e73790b7c46e2218308bd7, code=10130, countryId=1, name=广西, description=--]

WeatherProvince [id=58e74f37b7c46e1cf0b9de18, code=10117, countryId=1, name=宁夏, description=--]

WeatherProvince [id=58e74fa5b7c46e04207caeba, code=10101, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753b3b7c46e208413be36, code=10102, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753c3b7c46e1c98e3c4ff, code=10103, countryId=1, name=北京, description=--]

1

2

3

4

5WeatherProvince[id=58e73790b7c46e2218308bd7,code=10130,countryId=1,name=广西,description=--]

WeatherProvince[id=58e74f37b7c46e1cf0b9de18,code=10117,countryId=1,name=宁夏,description=--]

WeatherProvince[id=58e74fa5b7c46e04207caeba,code=10101,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753b3b7c46e208413be36,code=10102,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753c3b7c46e1c98e3c4ff,code=10103,countryId=1,name=北京,description=--]

ii)使用 Spring Data MongoDB方法命名规则添加自定义查询方法:

Spring Data MongoDB的方法命令规则类似于 Spring Data JPA,因此我们还可以为ProvinceRepository添加自定义的方法。如:

Java

List findByCountryId(Long countryId);

1ListfindByCountryId(LongcountryId);

测试代码如下:

Java

/**

* 测试自定义查询方法

*/

@Test

public void testFindByCountryId(){

List provinces = provinceRepository.findByCountryId(1l);

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13/**

* 测试自定义查询方法

*/

@Test

publicvoidtestFindByCountryId(){

Listprovinces=provinceRepository.findByCountryId(1l);

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

输出如下:

WeatherProvince [id=58e73790b7c46e2218308bd7, code=10130, countryId=1, name=广西, description=--]

WeatherProvince [id=58e74f37b7c46e1cf0b9de18, code=10117, countryId=1, name=宁夏, description=--]

WeatherProvince [id=58e74fa5b7c46e04207caeba, code=10101, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753b3b7c46e208413be36, code=10102, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753c3b7c46e1c98e3c4ff, code=10103, countryId=1, name=北京, description=--]

WeatherProvince [id=58f32e94cb4e640f24308405, code=10121, countryId=1, name=浙江, description=Sun Apr 16 16:43:00 GMT+08:00 2017]

1

2

3

4

5

6

7WeatherProvince[id=58e73790b7c46e2218308bd7,code=10130,countryId=1,name=广西,description=--]

WeatherProvince[id=58e74f37b7c46e1cf0b9de18,code=10117,countryId=1,name=宁夏,description=--]

WeatherProvince[id=58e74fa5b7c46e04207caeba,code=10101,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753b3b7c46e208413be36,code=10102,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753c3b7c46e1c98e3c4ff,code=10103,countryId=1,name=北京,description=--]

WeatherProvince[id=58f32e94cb4e640f24308405,code=10121,countryId=1,name=浙江,description=SunApr1616:43:00GMT+08:002017]

如果说上面添加的查询方法需要遵守 Spring Data MongoDB的方法命名规则的话,[email protected]�规则的自定义方法。如:

Java

@Query("{'country_id' : 1,'name' : ?0}")

List findChineseProvinces(String name);

1

2@Query("{'country_id' : 1,'name' : ?0}")

ListfindChineseProvinces(Stringname);

需要注意的是,这里设置了一个固定查询条件:’country_id’字段的值必须为1,同时将该方法的第一个参数映射成了“?0”并赋值给查询条件中的’name’,如果有多个参数的话,它们可以通过“?1”、“?2”等方式进行引用

测试代码如下:

Java

/**

* 测试多个查询条件

*/

@Test

public void testFindChineseProvinces(){

List provinces = provinceRepository.findChineseProvinces("北京");

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13/**

* 测试多个查询条件

*/

@Test

publicvoidtestFindChineseProvinces(){

Listprovinces=provinceRepository.findChineseProvinces("北京");

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

输出如下:

WeatherProvince [id=58e74fa5b7c46e04207caeba, code=10101, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753b3b7c46e208413be36, code=10102, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753c3b7c46e1c98e3c4ff, code=10103, countryId=1, name=北京, description=--]

1

2

3WeatherProvince[id=58e74fa5b7c46e04207caeba,code=10101,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753b3b7c46e208413be36,code=10102,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753c3b7c46e1c98e3c4ff,code=10103,countryId=1,name=北京,description=--]

iv)混合自定义复杂逻辑的方法:

[email protected]�们的基本查询需求的话,那么我们还可以通过定义一个中间接口来申明其他的复杂逻辑方法。最后则是将这些方法混合到MongoRepository自动生成的基本方法中。其实现步骤如下:

1.定义一个类保存我们其他所有自定义方法:

Java

package cn.zifangsky.mapper.mongodb;

import java.util.List;

import cn.zifangsky.model.mongodb.WeatherProvince;

public interface ProvinceOperations {

/**

* 只查询国内省市,国外则返回null

* @param provinceName

* @param domestic 是否是国内省市

* @return

*/

List findProvincesByContions(String provinceName,Boolean domestic);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16packagecn.zifangsky.mapper.mongodb;

importjava.util.List;

importcn.zifangsky.model.mongodb.WeatherProvince;

publicinterfaceProvinceOperations{

/**

* 只查询国内省市,国外则返回null

* @param provinceName

* @param domestic 是否是国内省市

* @return

*/

ListfindProvincesByContions(StringprovinceName,Booleandomestic);

}

2.为前面的ProvinceRepository定义一个实现类——ProvinceRepositoryImpl,该类继承上面的ProvinceOperations接口:

Java

package cn.zifangsky.mapper.mongodb;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.mongodb.core.MongoOperations;

import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;

import cn.zifangsky.model.mongodb.WeatherProvince;

public class ProvinceRepositoryImpl implements ProvinceOperations {

@Autowired

private MongoOperations mOperations;

@Override

public List findProvincesByContions(String provinceName,Boolean domestic) {

if(domestic){

Query query = Query.query(Criteria.where("name").is(provinceName)

.and("country_id").is(1));

return mOperations.find(query, WeatherProvince.class,"province");

}else{

return null;

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30packagecn.zifangsky.mapper.mongodb;

importjava.util.List;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.data.mongodb.core.MongoOperations;

importorg.springframework.data.mongodb.core.query.Criteria;

importorg.springframework.data.mongodb.core.query.Query;

importcn.zifangsky.model.mongodb.WeatherProvince;

publicclassProvinceRepositoryImplimplementsProvinceOperations{

@Autowired

privateMongoOperationsmOperations;

@Override

publicListfindProvincesByContions(StringprovinceName,Booleandomestic){

if(domestic){

Queryquery=Query.query(Criteria.where("name").is(provinceName)

.and("country_id").is(1));

returnmOperations.find(query,WeatherProvince.class,"province");

}else{

returnnull;

}

}

}

这里通过MongoOperations实现了我们自定义方法的细节。需要注意的是,这里的ProvinceRepositoryImpl命名规则默认为前面的“ProvinceRepository”其后面添加“Impl”,如果需要改成其他的名称,如:ProvinceRepositoryStuff,则需要修改最前面的 Spring Data MongoDB的JavaConfig的repositoryImplementationPostfix参数

3.ProvinceRepository继承上面定义的ProvinceOperations接口:

Java

package cn.zifangsky.mapper.mongodb;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

import org.springframework.data.mongodb.repository.Query;

import cn.zifangsky.mapper.mongodb.ProvinceOperations;

import cn.zifangsky.model.mongodb.WeatherProvince;

public interface ProvinceRepository extends MongoRepository,ProvinceOperations{

List findByCountryId(Long countryId);

@Query("{'country_id' : 1,'name' : ?0}")

List findChineseProvinces(String name);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19packagecn.zifangsky.mapper.mongodb;

importjava.util.List;

importorg.springframework.data.mongodb.repository.MongoRepository;

importorg.springframework.data.mongodb.repository.Query;

importcn.zifangsky.mapper.mongodb.ProvinceOperations;

importcn.zifangsky.model.mongodb.WeatherProvince;

publicinterfaceProvinceRepositoryextendsMongoRepository,ProvinceOperations{

ListfindByCountryId(LongcountryId);

@Query("{'country_id' : 1,'name' : ?0}")

ListfindChineseProvinces(Stringname);

}

测试代码如下:

Java

/**

* 测试自定义复杂查询条件

*/

@Test

public void testFindProvincesByContions(){

List provinces = provinceRepository.findProvincesByContions("北京",true);

if(provinces != null){

for(WeatherProvince province : provinces){

System.out.println(province);

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13/**

* 测试自定义复杂查询条件

*/

@Test

publicvoidtestFindProvincesByContions(){

Listprovinces=provinceRepository.findProvincesByContions("北京",true);

if(provinces!=null){

for(WeatherProvinceprovince:provinces){

System.out.println(province);

}

}

}

输出如下:

WeatherProvince [id=58e74fa5b7c46e04207caeba, code=10101, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753b3b7c46e208413be36, code=10102, countryId=1, name=北京, description=--]

WeatherProvince [id=58e753c3b7c46e1c98e3c4ff, code=10103, countryId=1, name=北京, description=--]

1

2

3WeatherProvince[id=58e74fa5b7c46e04207caeba,code=10101,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753b3b7c46e208413be36,code=10102,countryId=1,name=北京,description=--]

WeatherProvince[id=58e753c3b7c46e1c98e3c4ff,code=10103,countryId=1,name=北京,description=--]

至此,关于如何在Java中操作MongoDB的基本介绍就到此结束了,刚兴趣的同学可以自己安装一个MongoDB,参考上面代码并结合官方文档自己动手练习一下

mongo java 注解,在Java中使用Spring Data MongoDB操作Mong | zifangsky的个人博客相关推荐

  1. mongodb数据库java接口,MongoDB —— 使用Spring Data MongoDB操作数据库

    我们使用Spring Data MongoDB可以方便的在Spring boot项目中操作MongoDB 文档地址:https://docs.spring.io/spring-boot/docs/2. ...

  2. SpringBoot 集成 Spring Data Mongodb 操作 MongoDB 详解

    一.MongoDB 简介 MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,且与关系数据库的最为相像的.它支持的数据结构非常松散,是类似 json 的 bso ...

  3. Spring Data MongoDB中的审核实体

    Spring Data MongoDB 1.2.0静默引入了新功能:支持基本审核 . 因为您不会在本文的官方参考中找到太多有关它的信息,所以我将展示它带来的好处,如何配置Spring以进行审计以及如何 ...

  4. Spring Data MongoDB示例

    Spring Data MongoDB示例 欢迎使用Spring Data MongoDB示例.Spring Data MongoDB是将Spring Framework与最广泛使用的NoSQL数据库 ...

  5. mongo java 日期,Java 8日期/时间(JSR-310)类型与Spring Data MongoDB的映射

    我有Java 8日期/时间字段的简单文档 @Document public class Token { private Instant createdAt; ... } 我希望坚持使用Spring D ...

  6. Spring Data MongoDB级联保存在DBRef对象上

    默认情况下, Spring Data MongoDB不支持对带有@DBRef注释的引用对象的级联操作,如引用所述 : 映射框架不处理级联保存 . 如果更改了Person对象引用的Account对象,则 ...

  7. 使用NoSQLUnit测试Spring Data MongoDB应用程序

    Spring Data MongoDB是Spring Data项目中的项目,它提供了Spring编程模型的扩展,用于编写使用MongoDB作为数据库的应用程序. 要使用NoSQLUnit为Spring ...

  8. 使用Spring访问Mongodb的方法大全——Spring Data MongoDB查询指南

    1.概述 Spring Data MongoDB 是Spring框架访问mongodb的神器,借助它可以非常方便的读写mongo库.本文介绍使用Spring Data MongoDB来访问mongod ...

  9. Spring Data MongoDB教程

    在当今世界,尽快启动并运行应用程序非常重要. 该应用程序还应该易于开发和维护. Spring是这样的框架,它提供了与许多不同框架的集成的简便性,这使得使用Spring开发应用程序变得容易. 一种这样的 ...

最新文章

  1. arm-linux交叉编译工具链的制作(基于S3C2440)【转】
  2. c# mysql timeout expired_C#百万数据查询出现超时问题的解决方法
  3. mac os 录屏快捷键_Mac跨平台自动同步记事本
  4. Java开发人员应该知道的前20个库和API
  5. 该虚拟机似乎正在使用
  6. 超详细 图解 : IntelliJ IDEA 逆向生成 JAVA 实体类
  7. 写了 10 年代码之后,我学到的 7 个绝对真理
  8. hive python脚本,Hive调用Python脚本错误
  9. wxpython 基本的控件 (按钮)
  10. hololens与混合现实开发pdf_增强现实与虚拟现实:过去和未来
  11. 如何把电脑的计算机固定在桌面上,如何将Win7便签固定在电脑桌面上?
  12. 常见的Markdownpad2运行破解以及This view has crashed!报错和Awesomium1.6.6SDK安装使用
  13. 计算机键盘按键错乱,笔记本键盘按键错乱怎么办 解决笔记本电脑个别按键功能错乱...
  14. Uniapp 动态修改状态栏、导航栏背景色、字体图标颜色插件 Ba-AppBar
  15. c语言计算输入20个有符号整数,统计正整数,零,负整数的个数.操作,输入20个有符号整数,统计正整数.零.负整数的个数.并分别计算之和...
  16. 新浪出输入法了,深蓝词库转换更新到1.3.1——增加对新浪拼音输入法的支持
  17. Windows7瘦身优化
  18. ip地址、子网掩码、网段、子网划分
  19. ThinkPhp学习笔记——创建数据数据库中的表单
  20. oracle查询坐标在范围之内,lbs中从库中查询某经纬度2KM范围内的数据

热门文章

  1. 我用Python制作了全国疫情地图,其实一点都不难!
  2. 第七课:BootRom的烧录
  3. 拼多多参谋在什么地方?多多参谋的作用是什么?
  4. 网络学习之网络通信设备辨析
  5. CSS基础10-单行/多行文本溢出省略
  6. CPU 的工作原理以及为什么Apple Silicon M1 比 Intel i9 快?
  7. 平板插上显示无服务器,教你一招,让ipad变成免费的外置显示器!
  8. 【前端全家桶】 HTTP协议类
  9. C语言学生成绩信息管理系统课程设计报告
  10. opencv 中x,y,height, width,rows,cols 的关系