New project to use mongodb, then the installation mongodb linux on a virtual environment on a personal computer, a familiar practice.
1, start mongodb on the virtual machine.
First, view the virtual machine ip address, forget ha ~ ~
Command Line> ifconfig
mongodb installation directory bin> sudo ./mongod -f mongodb.conf
Check that has been started:
You can also use client connections:
2, the establishment of mongoProj engineering SpringBoot;
2.1, profile settings
pom.xml
<!-- mongodb 配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
First, single-source configuration, as follows:
#mongodb 配置 spring.data.mongodb.uri=mongodb://long:[email protected]:27017/long
2.2, write entity class, in this case mongo collection of casually from the name, create a Person class here
package com.example.demo.dto; public class Person { private static final long serialVersionUID = -3258839839160856613L; private String name; private int age; private String gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender='" + gender + '\'' + '}'; } }
2.3, create a DAO layer:
package com.example.demo.dao; import com.example.demo.dto.Person; public interface IPersonDao { public Person findPersonByName(String name); }
package com.example.demo.dao.impl; import com.example.demo.dao.IPersonDao; import com.example.demo.dto.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; @Repository public class PersonDaoImpl implements IPersonDao { @Autowired private MongoTemplate mongoTemplate; @Override public Person findPersonByName(String name) { Query query=new Query(Criteria.where("name").is(name)); //这里需要指定col集合 Person p = mongoTemplate.findOne(query,Person.class,"col"); return p; } }
2.4 Test categories:
package com.example.demo; import com.example.demo.dao.IPersonDao; import com.example.demo.dto.Person; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class MongoDbTest { @Autowired private IPersonDao ipersonDao; @Test public void findPersonByName(){ Person p =ipersonDao.findPersonByName("Jkson"); System.out.println(">>>>Person ="+p); } }
Test Results: