Databases 13 min read

Integrating MongoDB into Spring Boot: Manage Product Browsing History

This tutorial walks through integrating MongoDB into a Spring Boot mall project, covering installation, configuration, Spring Data MongoDB usage, defining document and repository classes, implementing service and controller layers, and testing CRUD operations for product browsing records.

macrozheng
macrozheng
macrozheng
Integrating MongoDB into Spring Boot: Manage Product Browsing History

Project Framework Overview

The article explains how to integrate MongoDB into a mall project to handle product browsing records, demonstrating add, delete, and query operations.

MongoDB

MongoDB is a database system built for rapid development of internet web applications, designed for high read/write throughput and automatic disaster recovery scalability.

MongoDB Installation and Usage

1. Download the MongoDB installer from official site .

2. Choose the installation path and install.

MongoDB installation directory
MongoDB installation directory

3. Create

data\db

and

data\log

folders under the installation path.

MongoDB data directories
MongoDB data directories

4. Create a

mongod.cfg

configuration file:

<code>systemLog:
  destination: file
  path: D:\developer\env\MongoDB\data\log\mongod.log
storage:
  dbPath: D:\developer\env\MongoDB\data\db
</code>

5. Install MongoDB as a Windows service (run with administrator privileges):

<code>D:\developer\env\MongoDB\bin\mongod.exe --config "D:\developer\env\MongoDB\mongod.cfg" --install</code>

Service commands:

<code>net start MongoDB   // start service
net stop MongoDB    // stop service
D:\developer\env\MongoDB\bin\mongod.exe --remove   // remove service</code>

6. Download the Robo 3T client from Robo 3T and connect to

localhost:27017

.

Robo 3T connection
Robo 3T connection

Spring Data MongoDB

Similar to Spring Data Elasticsearch, Spring Data MongoDB provides a Spring‑Data‑style way to operate on MongoDB, reducing boilerplate code.

Common Annotations

@Document

: marks a class as a MongoDB document.

@Id

: marks the ID field.

@Indexed

: creates an index on a field.

Derived Queries

Define query methods directly in the repository interface; Spring Data generates the implementation. Example: fetch browsing records for a member ordered by creation time descending.
<code>/**
 * Member product browsing history repository
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory, String> {
    /**
     * Find browsing records by memberId ordered by createTime descending
     */
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}
</code>

Integrating MongoDB for Document Operations

Add Dependency in pom.xml

<code><!--- mongodb related dependency -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</code>

Configure application.yml

<code>mongodb:
  host: localhost   # connection address
  port: 27017       # connection port
  database: mall-port   # database name
</code>

Define Document Class MemberReadHistory

<code>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;

/**
 * User product browsing history
 */
@Document
public class MemberReadHistory {
    @Id
    private String id;
    @Indexed
    private Long memberId;
    @Indexed
    private Long productId;
    private String memberNickname;
    private String memberIcon;
    private String productName;
    private String productPic;
    private String productSubTitle;
    private String productPrice;
    private Date createTime;
    // getters and setters omitted
}
</code>

Create Repository Interface

<code>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;

/**
 * Member product browsing history repository
 */
public interface MemberReadHistoryRepository extends MongoRepository<MemberReadHistory, String> {
    List<MemberReadHistory> findByMemberIdOrderByCreateTimeDesc(Long memberId);
}
</code>

Service Layer

<code>package com.macro.mall.tiny.service;

import com.macro.mall.tiny.nosql.mongodb.document.MemberReadHistory;
import java.util.List;

/**
 * Member browsing history management service
 */
public interface MemberReadHistoryService {
    int create(MemberReadHistory memberReadHistory);
    int delete(List<String> ids);
    List<MemberReadHistory> list(Long memberId);
}
</code>

Service Implementation

<code>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
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 mr = new MemberReadHistory();
            mr.setId(id);
            deleteList.add(mr);
        }
        memberReadHistoryRepository.deleteAll(deleteList);
        return ids.size();
    }

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

Controller Layer

<code>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;

@Api(tags = "MemberReadHistoryController", description = "Member product browsing history management")
@RequestMapping("/member/readHistory")
@Controller
public class MemberReadHistoryController {
    @Autowired
    private MemberReadHistoryService memberReadHistoryService;

    @ApiOperation("Create browsing record")
    @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("Delete browsing records")
    @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("List browsing records")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<MemberReadHistory>> list(Long memberId) {
        List<MemberReadHistory> memberReadHistoryList = memberReadHistoryService.list(memberId);
        return CommonResult.success(memberReadHistoryList);
    }
}
</code>

Interface Testing

Add Browsing Record to MongoDB

Add record via API
Add record via API
Response after adding
Response after adding

Query Browsing Records from MongoDB

Query result
Query result
Record list
Record list

Project Source Code

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

Recommended Reading

mall Architecture Overview

Required Knowledge for mall Learning

Setup SpringBoot + MyBatis Skeleton

Integrate Swagger‑UI for API Docs

Integrate Redis for Caching

SpringSecurity & JWT Authentication (Part 1)

SpringSecurity & JWT Authentication (Part 2)

SpringTask for Scheduled Jobs

Elasticsearch for Product Search

Follow us
Follow us

Welcome to follow and give a thumbs up!

BackendSpring BootMongoDBSpring DataDatabase IntegrationProduct Browsing
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.