Environmental dependency
Introduce spring-boot-starter-data-mongodb dependencies in the Pom file:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-data-mongodb</artifactid> </dependency>
Data Source Configuration
If the MongoDB port is the default port and no password is set, Sprinboot will turn on the default.
SPRING.DATA.MONGODB.URI=MONGODB://localhost:27017/springboot-db
MongoDB sets the password so that it is configured:
SPRING.DATA.MONGODB.URI=MONGODB://name:[email protected]:27017/dbname
To define a simple entity
Mongodb
PackageCn.tao.domain;Importorg.springframework.data.mongodb.core.mapping.Document; @Document (Collection= "T_customer") Public classCustomer {
PublicString _id; PublicString Carnumber; PublicString get_id () {return_id; } Public voidset_id (String _id) { This. _id =_id; } PublicString Getcarnumber () {returnCarnumber; } Public voidSetcarnumber (String carnumber) { This. Carnumber =Carnumber; }}
据操作dao层
@Repository
Public Interface extends Mongorepository<customer, string> { //publicCustomer Findbyfirstname (String FirstName); Public list<customer> findbylastname (String lastName);}
Write an interface, inherit mongorepository, this interface has several curd functions. If you want to customize some queries, such as queries based on FirstName, and get queries based on LastName, you only need to define a method. Note that FirstName strictly corresponds to the fields stored in MongoDB. In a typical Java application, the method of writing such an interface needs to be implemented by itself, but in springboot, you only need to write an interface name and corresponding parameters in the format, because Springboot has helped you achieve it.
Controller invocation Mode
PackageCn.tao.controller;Importcn.tao.domain.KdVehicle;Importcn.tao.repository.KdVehicleRepository;//import Cn.tao.service.MongoService;ImportCn.tao.service.SynService;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.data.mongodb.core.MongoTemplate;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;Importjava.util.List, @RestController @requestmapping ("/mongo") Public classMongocontroller {@AutowiredPrivatekdvehiclerepository kdvehiclerepository; @AutowiredPrivatemongotemplate mongotemplate; /*** Process differential data between Excel and database **/@RequestMapping ("/list") PublicList<customer> Dobegin ()throwsException {List<Customer> list =Kdvehiclerepository.findall (); //list<kdvehicle> list2 = Mongotemplate.findall (Customer.class);//can also returnlist; }}
Springboot Integrated MongoDB