首页 > 解决方案 > 用于获取与给定列表相似的相似列表的 Spring JPA 查询

问题描述

我有一个名为Product. 它还链接到product数据库表。数据库服务器是 PostgreSQL。我正在使用 Spring Boot 和 Hibernate。

public class Product{
    @ToString.Exclude
    @ElementCollection
    @Nullable
    private List<String> labels;
}

该类Product具有labels表示照片中对象的字段product。例如,

List<String> labels = ["apple", "table", "phone"]

我的主要目的是我想编写一个 SQL 查询来获取所有具有“相似标签”的产品。

什么是我的“相似标签”?例如,letlabels1表示 的标签,product1letlabels2表示 的标签product2

List<String> labels1 = ["apple", "table", "phone"]
List<String> labels2 = ["apple"]

两个列表中只有 1 项是 "apple"相同。所以sameItemCounter等于1

两个列表中的总不同项目列表等于,

distinctItemList = ["apple","table","phone"]

所以,distinctItemCounter等于3

如果100*sameItemCounter/distincItemCounter大于 30 then ,则两个标签列表是“相似标签”。

所以在这种情况下,100*sameItemCounter/distincItemCounteris 等于33,3大于30,那么我们可以说labels1labels2是“相似标签”。所以,相对而言,我们可以说product1product2是“同类产品”。

虽然我可以通过获取数据库中的所有产品而不是在 Spring Boot(后端)中创建所有进程来实现这一点,但我想通过数据库查询来完成所有这些进程。

我想要一个类似于这种形式的答案:

public static final String GET_ALL_SIMILAR_PRODUCTS = "query??";

@Query(value = FIND_PROJECTS, nativeQuery = true)
public List<Product> getAllSimilarProducts(Product p); // need to return all "similar products" of p.

我怎样才能做到这一点?

标签: sqlspringpostgresqlhibernatespring-data-jpa

解决方案


推荐阅读