SpringBoot开发案例之整合mongoDB

摘要:开始前,建议大家去了解以下文章,当然不看也没问题:MongoDB从入门到“精通”之简介和如何安装MongoDB从入门到“精通”之如何优雅的安装MongoDB从入门到“精通”之整合JavaWeb项目开发环境JDK1.

mongodb

开始前,建议大家去了解以下文章,当然不看也没问题:

MongoDB从入门到“精通”之简介和如何安装

MongoDB从入门到“精通”之如何优雅的安装

MongoDB从入门到“精通”之整合JavaWeb项目

开发环境

JDK1.7、Maven、Eclipse、SpringBoot1.5.2、mongodb3.4,Robomongo(可视化工具)

项目结构

mongodb

相关配置

pom.xml:

<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.itstyle.mongodb</groupId>

<artifactId>spring-boot-mongodb</artifactId>

<packaging>jar</packaging>

<version>0.0.1-SNAPSHOT</version>

<name>spring-boot-mongodb</name>

<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<java.version>1.7</java.version>

</properties>

<!--spring-boot-starter-parent包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写<version>版本号-->

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.2.RELEASE</version>

<relativePath/>

</parent>

<!--配置依赖-->

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-mongodb</artifactId>

</dependency>

</dependencies>

<build>

<plugins>

<!--打包项目mvncleanpackage-->

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

<dependencies>

<!--mvnspring-boot:run热部署启动-->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>springloaded</artifactId>

<version>1.4.0.RELEASE</version>

</dependency>

</dependencies>

</plugin>

</plugins>

</build>

</project>

实体类Users.java:

packagecom.itstyle.mongodb.model;

importjava.io.Serializable;

importorg.springframework.data.annotation.Transient;

importorg.springframework.data.mongodb.core.index.CompoundIndex;

importorg.springframework.data.mongodb.core.index.CompoundIndexes;

importorg.springframework.data.mongodb.core.index.Indexed;

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

@Document(collection="users")

@CompoundIndexes({

@CompoundIndex(name="age_idx",def="{'name':1,'age':-1}")

})

publicclassUsersimplementsSerializable{

privatestaticfinallongserialVersionUID=1L;

@Indexed

privateStringuid;

privateStringname;

privateintage;

@Transient

privateStringaddress;

publicUsers(Stringuid,Stringname,intage){

super();

this.uid=uid;

this.name=name;

this.age=age;

}

publicStringgetUid(){

returnuid;

}

publicvoidsetUid(Stringuid){

this.uid=uid;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

this.name=name;

}

publicintgetAge(){

returnage;

}

publicvoidsetAge(intage){

this.age=age;

}

publicStringgetAddress(){

returnaddress;

}

publicvoidsetAddress(Stringaddress){

this.address=address;

}

@Override

publicStringtoString(){

returnString.format(

"Customer[name='%s',age='%s']",

name,age);

}

}

业务接口IUserService.java:

packagecom.itstyle.mongodb.service;

importjava.util.List;

importcom.itstyle.mongodb.model.Users;

/**

*mongodb案例

*创建者小柒

*创建时间2017年7月19日

*

*/

publicinterfaceIUserService{

publicvoidsaveUser(Usersusers);

publicUsersfindUserByName(Stringname);

publicvoidremoveUser(Stringname);

publicvoidupdateUser(Stringname,Stringkey,Stringvalue);

publicList<Users>listUser();

}

业务实现UserServiceImpl.java:

packagecom.itstyle.mongodb.service.impl;

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;

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

importorg.springframework.stereotype.Component;

importcom.itstyle.mongodb.model.Users;

importcom.itstyle.mongodb.service.IUserService;

@Component("userService")

publicclassUserServiceImplimplementsIUserService{

@Autowired

MongoOperationsmongoTemplate;

publicvoidsaveUser(Usersusers){

mongoTemplate.save(users);

}

publicUsersfindUserByName(Stringname){

returnmongoTemplate.findOne(

newQuery(Criteria.where("name").is(name)),Users.class);

}

publicvoidremoveUser(Stringname){

mongoTemplate.remove(newQuery(Criteria.where("name").is(name)),

Users.class);

}

publicvoidupdateUser(Stringname,Stringkey,Stringvalue){

mongoTemplate.updateFirst(newQuery(Criteria.where("name").is(name)),

Update.update(key,value),Users.class);

}

publicList<Users>listUser(){

returnmongoTemplate.findAll(Users.class);

}

}

启动类Application.java:

packagecom.itstyle.mongodb;

importorg.apache.log4j.Logger;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;

importorg.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration

@ComponentScan(basePackages={"com.itstyle.mongodb"})

publicclassApplication{

privatestaticfinalLoggerlogger=Logger.getLogger(Application.class);

publicstaticvoidmain(String[]args)throwsInterruptedException{

SpringApplication.run(Application.class,args);

logger.info("项目启动");

}

}

基础配置application.properties:

#项目contextPath,一般在正式发布版本中

server.context-path=/mongodb

#服务端口

server.port=8080

#session最大超时时间(分钟),默认为30

server.session-timeout=60

#该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置

#server.address=192.168.16.11

#tomcat最大线程数,默认为200

server.tomcat.max-threads=800

#tomcat的URI编码

server.tomcat.uri-encoding=UTF-8

#mongo2.x支持以上两种配置方式mongo3.x仅支持uri方式

#mongodbnote:mongo3.xwillnotusehostandport,onlyuseuri

#spring.data.mongodb.host=192.168.1.180

#spring.data.mongodb.port=27017

#spring.data.mongodb.database=itstyle

#没有设置密码

#spring.data.mongodb.uri=mongodb://192.168.1.180:27017/itstyle

#设置了密码

spring.data.mongodb.uri=mongodb://itstyle:[email protected]:27017/itstyle

测试类SpringbootMongodbApplication.java:

packagecom.itstyle.mongodb.test;

importjava.util.List;

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

importorg.springframework.boot.CommandLineRunner;

importorg.springframework.boot.SpringApplication;

importorg.springframework.boot.autoconfigure.SpringBootApplication;

importorg.springframework.context.annotation.ComponentScan;

importcom.itstyle.mongodb.model.Users;

importcom.itstyle.mongodb.service.IUserService;

@SpringBootApplication

@ComponentScan(basePackages={"com.itstyle.mongodb"})

publicclassSpringbootMongodbApplicationimplementsCommandLineRunner{

@Autowired

privateIUserServiceuserService;

publicstaticvoidmain(String[]args){

SpringApplication.run(SpringbootMongodbApplication.class,args);

}

@Override

publicvoidrun(String...args)throwsException{

try{

Usersusers=newUsers("1","小明",10);

users.setAddress("青岛市");

userService.saveUser(users);

List<Users>list=userService.listUser();

System.out.println("一共这么多人:"+list.size());

}catch(Exceptione){

e.printStackTrace();

}

}

}

最后,运行测试类,使用可视化工具Robomongo查看:

keshihua

注解说明

@Document

标注在实体类上,与hibernate异曲同工。

@Document(collection="users")

publicclassUsersimplementsSerializable{

privatestaticfinallongserialVersionUID=1L;

...省略代码

@CompoundIndex

复合索引,加复合索引后通过复合索引字段查询将大大提高速度。

@Document(collection="users")

@CompoundIndexes({

@CompoundIndex(name="age_idx",def="{'name':1,'age':-1}")

})

publicclassUsersimplementsSerializable{

privatestaticfinallongserialVersionUID=1L;

...省略代码

@Id

MongoDB默认会为每个document生成一个_id属性,作为默认主键,且默认值为ObjectId,可以更改_id的值(可为空字符串),但每个document必须拥有_id属性。

当然,也可以自己设置@Id主键,不过官方建议使用MongoDB自动生成。

@Indexed

声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。

唯一索引的话是@Indexed(unique=true)。

也可以对数组进行索引,如果被索引的列是数组时,mongodb会索引这个数组中的每一个元素。

@Indexed

privateStringuid;

@Transient

被该注解标注的,将不会被录入到数据库中。只作为普通的javaBean属性。

@Transient

privateStringaddress;

@Field

代表一个字段,可以不加,不加的话默认以参数名为列名。

@Field("firstName")

privateStringname;

当然了,以上的以上,可能仅仅是冰山一角,还有很多特性等待大家去挖掘。

代码:http://git.oschina.net/52itstyle/spring-boot-mongodb

作者:小柒

出处:https://blog.52itstyle.com

本文版权归作者和云栖社区所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出,如有问题,可邮件([email protected])咨询。

相关推荐