【问题标题】:Enforcing a Unique List of Values with Lombok or Mongo annotations on Data Model在数据模型上使用 Lombok 或 Mongo 注释强制执行唯一的值列表
【发布时间】:2021-07-16 21:21:12
【问题描述】:

是否有一种干净的方法可以使用注释强制列表响应中的所有值都是唯一的。理想情况下,我不想编写单独的代码来强制执行唯一的地址列表。

在下面的代码中,我希望我的 HashSet 地址(HashSet 地址)只有唯一值

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.ArrayList;

/**
 * User Address data class reflects the list of addresses each customer will send us
 *
 * {
 *   "accountId": "234234234",
 *   "addresses": [
 *     "234234242423423423423",
 *     "909897897981231231233",
 *   ]
 * }
 */
@Document(value="dbname")
@Data
public class UserAddresses {

    @Id
    private String accountId;

    private HashSet<String> addresses;

}

【问题讨论】:

  • 我不明白你的问题:Set 永远不会包含重复项(根据equals/hashCode)。
  • 由于某种原因,HashSet 允许重复,但在将行更改为 Set 后它起作用了。私有 HashSet 地址;
  • 不,Set 的任何实现都不会允许重复。它是一个集合的核心定义,不允许重复。您的代码肯定有其他问题,例如键上的 equals 或 hashCode 实现错误或缺失。

标签: mongodb spring-boot lombok


【解决方案1】:

只需将我的数据结构从 HashSet 更改为 Set 即可解决我的问题:

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.ArrayList;

/**
 * User Address data class reflects the list of addresses each customer will send us
 *
 * {
 *   "accountId": "234234234",
 *   "addresses": [
 *     "234234242423423423423",
 *     "909897897981231231233",
 *   ]
 * }
 */
@Document(value="dbname")
@Data
public class UserAddresses {

    @Id
    private String accountId;

    private Set<String> addresses;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多