通过Docker辅助开发------------Spring Data MongoDB

什么是容器?

容器是一种应用层的抽象,它是一种标准化的单元,容器不包含操作系统的相关细节和内容,使用容器相对于虚拟机来说,相对轻量级一些,它的开启与部署相对快。在本地使用Docker创建一个容器,用容器创建相应的基础设施。

Docker常用命令

镜像相关

docker run 的常用选项

docker run [OPTIONS] IMAGE [COMMAND] [ARG…]
选项说明

  • -d,后台运行容器
  • -e,设置环境变量
  • – expose / -p 宿主端口:容器端口
  • – name,指定容器名称
  • –link,链接不同容器
  • -v 宿主目录:容器目录,挂载磁盘卷

通过 Docker 启动 MongoDB(文档型的数据库)

获取镜像

  • docker pull mongo

运行 MongoDB 镜像

  • docker run --name mongo -p 27017:27017 -v ~/dockerdata/mongo:/data/db -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin -d mongo

通过 Docker 启动 MongoD

登录到MongoDB容器中

  • docker exec -it mongo bash

通过Shell连接MongoDB

  • mongo -u admin -p admin

Windows10下命令

  1. docker images (查看已经有的镜像)
  2. docker pull mongo(下载mongo镜像)
  3. docker volume create --name mongodata (创建数据卷)
  4. docker run --name mongo -p 27017:27017 -v mongodata:/data/db -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin -d mongo(新建并启动容器)
  5. docker start mongo (开启已有的容器)
  6. docker ps(查看启动中的容器 加参数-p 是查看全部的容器)
  7. docker exec -it mongo bash(登录到 MongoDB 容器)
  8. mongo -u admin -p admin(通过 Shell 连接 MongoDB)
  9. 创建一个库
  10. 创建一个用户名和密码
  11. 将相关配置写入application.properties中
  12. 敲代码

Spring Data MongoDB 的 Repository

**@EnableMongoRepositories **
将这个注解写在主方法上面,spring启动后,会自动去找有继承以下接口的接口

  • MongoRepository<T, ID>
    通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查
  • PagingAndSortingRepository<T, ID>
    这个接口提供了分页与排序功能
  • CrudRepository<T, ID>
    提供了最基本的对实体类的增、删、改、查操作

例子

/*
 * @Author: 13679
 * @CreateTime: 2019-11-23 10:37
 */  //Converter接口将Document转换为Money  Document 接口表示整个 HTML 或 XML 文档。从概念上讲,它是文档树的根,并提供对文档数据的基本访问。
public class MoneyReadConverter implements Converter<Document, Money> {
    @Override
    public Money convert(Document source) {
        //Document money = (Document) document.get("money");     //取得money
        //double amount = Double.parseDouble(money.getString("amount"));//在money当中解析出amount,有了amount之后,可以知道一个大概的金额
        //String curreny = ((Document) money.get("currency")).getString("code"); //从中,取出currency解析出code
        //return Money.of(CurrencyUnit.of(curreny),amount);//转换    CurrencyUnit.of代表的是货币类型
        Document money = (Document) source.get("money");
        double amount = Double.parseDouble(money.getString("amount"));
        String currency = ((Document) money.get("currency")).getString("code");
        return Money.of(CurrencyUnit.of(currency), amount);
    }
}


/**
 * @Author: 13679
 * @CreateTime: 2019-11-23 10:38
 */

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Document  //标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表。
@Data
public class Coffee {
    @Id
    private String id;
    private String name;
    private Money price;
    private Date createTime;
    private Date updateTime;

}

public interface CoffeeRepository extends MongoRepository<Coffee, String> {
    List<Coffee> findByName(String name);
}

/**
 * @Author: 13679
 * @CreateTime: 2019-11-23 10:38
 */
@Slf4j
@SpringBootApplication
@EnableMongoRepositories
public class MongoDemoApplicationtest implements ApplicationRunner {
    @Autowired
    private MongoTemplate mongoTemplate;

    public static void main(String[] args) {
        SpringApplication.run(MongoDemoApplicationtest.class, args);
    }


       //Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。(和xml配置中的bean标签的作用是一样的)
    @Bean
    public MongoCustomConversions mongoCustomConversions() {
        return new MongoCustomConversions(Arrays.asList(new MoneyReadConverter()));//MoneyReadConverter作为列表的成员加入
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Coffee espresso = Coffee.builder()
                .name("espresso")
                .price(Money.of(CurrencyUnit.of("CNY"),20.0))  //意思是 多少金额的哪国钱
                .createTime(new Date())
                .updateTime(new Date()).build();
        Coffee save = mongoTemplate.save(espresso);
        log.info("Coffee{}",save);

        List<Coffee> list = mongoTemplate.find(
                query(where("name").is("espresso")), Coffee.class);  //查询
        log.info("Find {} coffee",list.size());
        list.forEach(coffee -> log.info("coffee is {}",coffee));

        Thread.sleep(1000);//看更新时间
        UpdateResult updateResult = mongoTemplate.updateFirst(query(where("name").is("espresso")),
                new Update().set("price", Money.ofMajor(CurrencyUnit.of("CNY"), 30))
                        .currentDate("updatetime"), Coffee.class);
        log.info("update result {}", updateResult.getModifiedCount());
        Coffee byId = mongoTemplate.findById(save.getId(), Coffee.class);
        log.info("find coffee is {}",byId);
        mongoTemplate.remove(byId);
    }
}


@Slf4j
@SpringBootApplication
@EnableMongoRepositories
public class MongoRepositoryDemoApplication implements CommandLineRunner {
	@Autowired
	private CoffeeRepository coffeeRepository;

	public static void main(String[] args) {
		SpringApplication.run(MongoRepositoryDemoApplication.class, args);
	}

	@Bean
	public MongoCustomConversions mongoCustomConversions() {
		return new MongoCustomConversions(Arrays.asList(new MoneyReadConverter()));
	}

	@Override
	public void run(String... args) throws Exception {
		Coffee espresso = Coffee.builder()
				.name("espresso")
				.price(Money.of(CurrencyUnit.of("CNY"), 20.0))
				.createTime(new Date())
				.updateTime(new Date()).build();
		Coffee latte = Coffee.builder()
				.name("latte")
				.price(Money.of(CurrencyUnit.of("CNY"), 30.0))
				.createTime(new Date())
				.updateTime(new Date()).build();

		coffeeRepository.insert(Arrays.asList(espresso, latte));
		coffeeRepository.findAll(Sort.by("name"))
				.forEach(c -> log.info("Saved Coffee {}", c));

		Thread.sleep(1000);
		latte.setPrice(Money.of(CurrencyUnit.of("CNY"), 35.0));
		latte.setUpdateTime(new Date());
		coffeeRepository.save(latte);
		coffeeRepository.findByName("latte")
				.forEach(c -> log.info("Coffee {}", c));

		coffeeRepository.deleteAll();
	}
}

发布了59 篇原创文章 · 获赞 6 · 访问量 979

猜你喜欢

转载自blog.csdn.net/weixin_43790623/article/details/103099629