mall Mongodb achieve integration Document Actions

This article explains mall Mongodb the integration process to achieve product browsing history Mongodb the add, delete, query, for example.

Project uses the framework of introduction

Mongodb

Mongodb is a database system for the rapid development of Internet and Web applications built its model and data persistence strategy is to build high read / write throughput and high scalability automatic disaster recovery system.

Mongodb installation and use

  1. Mongodb download the installation package, download address: https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.2.21-signed.msi

  2. Installation Installation path selection

1939592-dcf541872b4bf22e.png
Show pictures /arch_screen_37.png
1939592-957bfc82ed899d74.png
Show pictures /arch_screen_38.png
  1. Creating data \ db and data \ log two folders in the installation path
1939592-da07e2f7f0f875ca.png
Show pictures /arch_screen_39.png
  1. Creating mongod.cfg configuration file in the installation path
systemLog:
    destination: file
    path: D:\developer\env\MongoDB\data\log\mongod.log
storage:
    dbPath: D:\developer\env\MongoDB\data\db
  1. Installed as a service (run command requires administrator privileges)
D:\developer\env\MongoDB\bin\mongod.exe --config "D:\developer\env\MongoDB\mongod.cfg" --install
1939592-b78d180e8af25ade.png
Show pictures /arch_screen_40.png
  1. Service-Related Commands
启动服务:net start MongoDB
关闭服务:net stop MongoDB
移除服务:D:\developer\env\MongoDB\bin\mongod.exe --remove
  1. Download the client program: https://download.robomongo.org/1.2.1/windows/robo3t-1.2.1-windows-x86_64-3e50a65.zip

  2. Unzip to the specified directory, open robo3t.exe and connect to localhost: 27017

1939592-5929ecb84c3f33fe.png
Show pictures /arch_screen_41.png

Spring Data Mongodb

And Spring Data Elasticsearch similar, Spring Data Mongodb is a way to Spring Data provided by Spring style to manipulate data stored, it can avoid writing a lot of boilerplate code.

Common Annotations

  • @Document: marked field is mapped to the object on the document Mongodb
  • @Id: marked a domain to domain ID
  • @Indexed: a field is marked Mongodb index field

Operation mode data Sping Data

Inheritance common method of operating a data interface can be obtained MongoRepository
1939592-67ff302842f5f4ef.png
Show pictures /arch_screen_42.png
The use of derivatives may query

Direct interface specified in the query methods can query name, without the need to achieve the following for the reverse acquisition history by Member id chronological examples.

/**
 * 会员商品浏览历史Repository
 * Created by macro on 2018/8/3.
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory,String> {
    /**
     * 根据会员id按时间倒序获取浏览记录
     * @param memberId 会员id
     */
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}

The idea will be prompted to direct the corresponding field

1939592-06a5b7e68c24455f.png
Show pictures /arch_screen_43.png
Use @Query annotation can be queried using the JSON query Mongodb
@Query("{ 'memberId' : ?0 }")
List<MemberReadHistory> findByMemberId(Long memberId);

Mongodb achieve integration Document Actions

Add its dependencies in pom.xml

<!---mongodb相关依赖-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

SpringBoot modify configuration files

Modify application.yml file, in spring: Add Mongodb related configuration data node.

mongodb:
  host: localhost # mongodb的连接地址
  port: 27017 # mongodb的连接端口号
  database: mall-port # mongodb的连接的数据库

Adding members History Document Object MemberReadHistory

Domain ID document object @Id add comments, you need to retrieve the field to add @Indexed comment.

package com.macro.mall.tiny.nosql.mongodb.document;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

/**
 * 用户商品浏览历史记录
 * Created by macro on 2018/8/3.
 */
@Document
public class MemberReadHistory {
    @Id
    private String id;
    @Indexed
    private Long memberId;
    private String memberNickname;
    private String memberIcon;
    @Indexed
    private Long productId;
    private String productName;
    private String productPic;
    private String productSubTitle;
    private String productPrice;
    private Date createTime;

    //省略了所有getter和setter方法

}

Adding an interface for operating the Mongodb MemberReadHistoryRepository

Inheritance MongoRepository interface, so it has some basic data Mongodb method of operation, while the definition of a derivative query methods.

package com.macro.mall.tiny.nosql.mongodb.repository;


import com.macro.mall.tiny.nosql.mongodb.document.MemberReadHistory;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * 会员商品浏览历史Repository
 * Created by macro on 2018/8/3.
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory,String> {
    /**
     * 根据会员id按时间倒序获取浏览记录
     * @param memberId 会员id
     */
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}

Add MemberReadHistoryService Interface

package com.macro.mall.tiny.service;


import com.macro.mall.tiny.nosql.mongodb.document.MemberReadHistory;

import java.util.List;

/**
 * 会员浏览记录管理Service
 * Created by macro on 2018/8/3.
 */
public interface MemberReadHistoryService {
    /**
     * 生成浏览记录
     */
    int create(MemberReadHistory memberReadHistory);

    /**
     * 批量删除浏览记录
     */
    int delete(List<String> ids);

    /**
     * 获取用户浏览历史记录
     */
    List<MemberReadHistory> list(Long memberId);
}

Add MemberReadHistoryService interface class MemberReadHistoryServiceImpl

package com.macro.mall.tiny.service.impl;

import com.macro.mall.tiny.nosql.mongodb.document.MemberReadHistory;
import com.macro.mall.tiny.nosql.mongodb.repository.MemberReadHistoryRepository;
import com.macro.mall.tiny.service.MemberReadHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 会员浏览记录管理Service实现类
 * Created by macro on 2018/8/3.
 */
@Service
public class MemberReadHistoryServiceImpl implements MemberReadHistoryService {
    @Autowired
    private MemberReadHistoryRepository memberReadHistoryRepository;
    @Override
    public int create(MemberReadHistory memberReadHistory) {
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        memberReadHistoryRepository.save(memberReadHistory);
        return 1;
    }

    @Override
    public int delete(List<String> ids) {
        List<MemberReadHistory> deleteList = new ArrayList<>();
        for(String id:ids){
            MemberReadHistory memberReadHistory = new MemberReadHistory();
            memberReadHistory.setId(id);
            deleteList.add(memberReadHistory);
        }
        memberReadHistoryRepository.deleteAll(deleteList);
        return ids.size();
    }

    @Override
    public List<MemberReadHistory> list(Long memberId) {
        return memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(memberId);
    }
}

Add MemberReadHistoryController defined interfaces

package com.macro.mall.tiny.controller;

import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.nosql.mongodb.document.MemberReadHistory;
import com.macro.mall.tiny.service.MemberReadHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会员商品浏览记录管理Controller
 * Created by macro on 2018/8/3.
 */
@Controller
@Api(tags = "MemberReadHistoryController", description = "会员商品浏览记录管理")
@RequestMapping("/member/readHistory")
public class MemberReadHistoryController {
    @Autowired
    private MemberReadHistoryService memberReadHistoryService;

    @ApiOperation("创建浏览记录")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult create(@RequestBody MemberReadHistory memberReadHistory) {
        int count = memberReadHistoryService.create(memberReadHistory);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("删除浏览记录")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("ids") List<String> ids) {
        int count = memberReadHistoryService.delete(ids);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("展示浏览记录")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MemberReadHistory>> list(Long memberId) {
        List<MemberReadHistory> memberReadHistoryList = memberReadHistoryService.list(memberId);
        return CommonResult.success(memberReadHistoryList);
    }
}

Interface test

Add items to your browsing history Mongodb

1939592-2b215f2ced502f56.png
Show pictures /arch_screen_44.png

1939592-93d2c32d6a575c70.png
Show pictures /arch_screen_45.png

Commodity history of queries Mongodb

1939592-ccbb83abdce9eea4.png
Show pictures /arch_screen_46.png

1939592-732491e8a0237fb2.png
Show pictures /arch_screen_47.png

Project Source Address

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-07

Guess you like

Origin blog.csdn.net/weixin_33890526/article/details/90821229