springboot整合集成mongodb

原创 创建时间:2019-06-08 访问量:16 赞:0 踩:0
compile 'org.springframework.boot:spring-boot-starter-data-mongodb'

配置:

# spring data 相关的配置
  data:
    mongodb:
      uri: mongodb://root:root@192.168.133.129:27017/admin
package com.fight.strive.sys.modules.mongodb.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.EnableMongoAuditing;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author ZHOUXIANG
 */
@Configuration
@EnableMongoAuditing
@EnableMongoRepositories(basePackages = "com.fight.strive.**.mongo")
public class MongoConfig {
}

测试:

Entity:

package com.fight.strive.sys.modules.mongodb.dto;

import com.fight.strive.sys.modules.jpa.entity.BaseEntity;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.util.Date;

@Data
@Accessors(chain = true)
@Document("test")
public class Student extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String id;

    private String name;

    private Integer age;

    private Date birthday;

}

Repository:

package com.fight.strive.sys.modules.mongodb.mongo;

import com.fight.strive.sys.modules.mongodb.dto.Student;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface StudentMongoRepository extends MongoRepository<Student, Long> {
}

Test:

package com.fight.strive.sys.modules.mongodb;

import com.fight.strive.StriveApplicationTests;
import com.fight.strive.sys.modules.mongodb.mongo.StudentMongoRepository;
import com.fight.strive.sys.modules.mongodb.dto.Student;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

public class MongoDBTests extends StriveApplicationTests {

    @Autowired
    private StudentMongoRepository studentMongoRepository;

    @Test
    public void testSaveStudent() {
        Student student = new Student();
        student.setName("zx").setAge(23).setBirthday(new Date());
        studentMongoRepository.save(student);
    }

}


评论
 我想说:
==已经到底了==
关注: 粉丝: 积分:
Copyright ©2018 工联信息网——打造最实用且免费的互联网资源共享社区
如有疑问和需求请致邮箱:need@glxxw2018.com
不良信息反馈及建议请致邮箱:accusation@glxxw2018.com
沪ICP备18018158号-1