欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot集成mongoDB(十二)

程序员文章站 2022-04-30 21:21:49
...

步骤

1.pom.xml引包

2.在配置application.properties中设置spring.data.mongodb.uri属性

3.建测试实体类类

4.编写数据操作接口

5.测试

1.pom.xml引包

<!--集成mongoDB-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2.在配置application.properties中设置spring.data.mongodb.uri属性

#mongo2.x支持以上两种配置方式 mongo3.x仅支持uri方式
#spring.data.mongodb.host=127.0.0.1
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=test

#没有设置密码
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test
#设置了密码
#spring.data.mongodb.uri=mongodb://root:[email protected]:27017/test

3.建测试实体类类

package com.ljl.spring.boot.entity;

import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import java.io.Serializable;


/**
 * 集成mongoDB测试实体类
 * @author alen
 * @create 2017-12-22 15:28
 **/
@Document(collection="person")
@CompoundIndexes({
        @CompoundIndex(name = "age_index", def = "{'name': 1, 'age': -1}")
})
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Indexed
    private String sysno;//命名成id,持久化到数据库会是_id,值将是自己设置的,不是系统生成的
    private String name;
    private int age;
    @Transient
    private String address;

    public Person(String sysno, String name, int age) {
        super();
        this.sysno = sysno;
        this.name = name;
        this.age = age;
    }

    public String getSysno() {
        return sysno;
    }

    public void setSysno(String sysno) {
        this.sysno = sysno;
    }

    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 getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[name='%s', age='%s']",
                name, age);
    }
}


4.编写数据操作接口

/**
 * @author alen
 * @create 2017-12-22 15:45
 **/
public interface PersonService {
     void savePerson(Person person);

     Person findPersonByName(String name);

     void removePerson(String name);

     void updatePerson(String name, String key, String value);

     List<Person> listPerson();
}
package com.ljl.spring.boot.service.Impl;

import com.ljl.spring.boot.entity.Person;
import com.ljl.spring.boot.service.PersonService;
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.stereotype.Component;

import java.util.List;

/**
 * 实现类
 * @author alen
 * @create 2017-12-22 15:48
 **/

@Component("personService")
public class PersonServiceImpl implements PersonService {
    @Autowired
    MongoOperations mongoTemplate;

    public void savePerson(Person person) {
        mongoTemplate.save(person);
    }

    public Person findPersonByName(String name) {
        return mongoTemplate.findOne(
                new Query(Criteria.where("name").is(name)), Person.class);
    }

    public void removePerson(String name) {
        mongoTemplate.remove(new Query(Criteria.where("name").is(name)),
                Person.class);
    }

    public void updatePerson(String name, String key, String value) {
        mongoTemplate.updateFirst(new Query(Criteria.where("name").is(name)),
                Update.update(key, value), Person.class);

    }

    public List<Person> listPerson() {
        return mongoTemplate.findAll(Person.class);
    }
}


5.测试

/**
 * 测试集成mongoDB
 * @author alen
 * @create 2017-12-22 15:57
 **/
@RestController
public class MongoDBController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/mongo")
    public List<Person> testMongo() {
        List<Person> list=null;
        try {
            Person person = new Person("1", "小明", 28);
            person.setAddress("上海");
            personService.savePerson(person);
            list = personService.listPerson();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}


注解说明

@Document

标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表。

@Document(collection="person")
@CompoundIndexes({
        @CompoundIndex(name = "age_index", def = "{'name': 1, 'age': -1}")
})
public class Person implements Serializable {


@CompoundIndex

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

@CompoundIndexes({
        @CompoundIndex(name = "age_index", def = "{'name': 1, 'age': -1}")
})
public class Person implements Serializable {

@Id

MongoDB默认会为每个document生成一个 _id 属性,作为默认主键,且默认值为ObjectId,可以更改 _id 的值(可为空字符串),但每个document必须拥有 _id 属性。当然,也可以自己设置@Id主键,不过官方建议使用MongoDB自动生成。

@Indexed

声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。
唯一索引的话是@Indexed(unique = true)。
也可以对数组进行索引,如果被索引的列是数组时,mongodb会索引这个数组中的每一个元素。

 @Indexed
    private String sysno;


@Transient

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

@Transient
private String address;

@Field

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

@Field("firstName")
private String name;

参考:

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-mongodb