Databases 11 min read

Mastering RedisOM: Elegant ORM for Spring Boot with Full-Text Search

RedisOM, the official Redis ORM for Java, lets Spring Boot developers replace RedisTemplate with object‑oriented data handling and built‑in full‑text search, covering JDK 11 setup, Maven dependencies, configuration, entity annotations, repository interfaces, and REST controller examples for managing product data.

macrozheng
macrozheng
macrozheng
Mastering RedisOM: Elegant ORM for Spring Boot with Full-Text Search
Previously in SpringBoot projects I used RedisTemplate to operate Redis data, which is the official Spring‑supported way but feels less elegant compared to Spring Data for MongoDB or Elasticsearch. Redis now offers its own ORM framework, RedisOM , which is more graceful and is recommended.

RedisOM Overview

RedisOM is the official Redis ORM, extending Spring Data Redis. Since Redis now supports native JSON storage, using RedisTemplate with stringified JSON is clumsy. RedisOM allows object‑oriented operations on Redis data and provides built‑in search capabilities.

JDK 11 Installation

RedisOM currently supports JDK 11 and above, so you must install it first.

Download JDK 11, preferably from the Tsinghua University Open Source Software Mirror: https://mirrors.tuna.tsinghua.edu.cn/AdoptOpenJDK/11/jdk/x64/

Download the compressed package, extract it to a designated directory.

In IDEA, set the module JDK version to JDK 11.

Usage

We will manage product information stored in Redis and implement product search. Ensure the full Redis stack RedisMod is installed; see the RediSearch tutorial for details.

Add RedisOM dependencies to pom.xml:

<!--Redis OM related dependency-->
<dependency>
    <groupId>com.redis.om</groupId>
    <artifactId>redis-om-spring</artifactId>
    <version>0.3.0-SNAPSHOT</version>
</dependency>

Add the snapshot repository:

<repositories>
    <repository>
        <id>snapshots-repo</id>
        <url>https://s01.oss.sonatype.org/content/repositories/snapshots/</url>
    </repository>
</repositories>

Configure Redis connection in application.yml:

spring:
  redis:
    host: 192.168.3.105  # Redis server address
    database: 0          # Default DB index
    port: 6379           # Port
    password:            # Password (empty if none)
    timeout: 3000ms      # Connection timeout

Enable RedisOM document repositories in the main class:

@SpringBootApplication
@EnableRedisDocumentRepositories(basePackages = "com.macro.mall.tiny.*")
public class MallTinyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MallTinyApplication.class, args);
    }
}

Create a product document entity annotated with @Document (language set to "chinese") and field annotations:

/**
 * Product entity
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Document(language = "chinese")
public class Product {
    @Id
    private Long id;
    @Indexed
    private String productSn;
    @Searchable
    private String name;
    @Searchable
    private String subTitle;
    @Indexed
    private String brandName;
    @Indexed
    private Integer price;
    @Indexed
    private Integer count;
}

Explanation of annotations: @Id: declares the primary key; RedisOM stores data using the fully‑qualified class name plus ID as the key. @Indexed: creates an index, usually for non‑text fields. @Searchable: creates a searchable index for text fields.

Create a repository interface extending RedisDocumentRepository:

/**
 * Product management repository
 */
public interface ProductRepository extends RedisDocumentRepository<Product, Long> {
    /** Find by brand name */
    List<Product> findByBrandName(String brandName);
    /** Search by name or subtitle */
    List<Product> findByNameOrSubTitle(String name, String subTitle);
}

Implement a REST controller that uses the repository for CRUD, pagination, and derived queries:

@RestController
@Api(tags = "ProductController", description = "Manage products with Redis OM")
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @ApiOperation("Import products")
    @PostMapping("/import")
    public CommonResult importList() {
        productRepository.deleteAll();
        List<Product> productList = LocalJsonUtil.getListFromJson("json/products.json", Product.class);
        for (Product product : productList) {
            productRepository.save(product);
        }
        return CommonResult.success(null);
    }

    @ApiOperation("Create product")
    @PostMapping("/create")
    public CommonResult create(@RequestBody Product entity) {
        productRepository.save(entity);
        return CommonResult.success(null);
    }

    @ApiOperation("Delete product")
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        productRepository.deleteById(id);
        return CommonResult.success(null);
    }

    @ApiOperation("Get product detail")
    @GetMapping("/detail/{id}")
    public CommonResult<Product> detail(@PathVariable Long id) {
        Optional<Product> result = productRepository.findById(id);
        return CommonResult.success(result.orElse(null));
    }

    @ApiOperation("Paginated query")
    @GetMapping("/page")
    public CommonResult<List<Product>> page(@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "5") Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Product> pageResult = productRepository.findAll(pageable);
        return CommonResult.success(pageResult.getContent());
    }

    @ApiOperation("Find by brand name")
    @GetMapping("/getByBrandName")
    public CommonResult<List<Product>> getByBrandName(String brandName) {
        List<Product> resultList = productRepository.findByBrandName(brandName);
        return CommonResult.success(resultList);
    }

    @ApiOperation("Search by keyword")
    @GetMapping("/search")
    public CommonResult<List<Product>> search(String keyword) {
        List<Product> resultList = productRepository.findByNameOrSubTitle(keyword, keyword);
        return CommonResult.success(resultList);
    }
}

When the application starts, RedisOM automatically creates indexes for the document fields.

Use Swagger to test the APIs, first importing products, then querying by ID, brand, or keyword.

Derived query methods follow Spring Data naming conventions; see the accompanying table for rules.

Conclusion

RedisOM provides an elegant way to work with Redis in Spring Boot, similar to Spring Data for MongoDB or Elasticsearch. It is currently only available as a snapshot version, but a stable release supporting JDK 8 is expected.

References

Project repository: https://github.com/redis/redis-om-spring

Official documentation: https://developer.redis.com/develop/java/spring/redis-om/redis-om-spring-json

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavadatabaseredisSpring BootORMFull‑Text SearchRedisOM
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

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.