可以为 FLOAT 的约束 'javax.validation.constraints.Size' 找到节点验证器

Node validator could be found for constraints 'javax.validation.constraints.Size' for FLOAT

发帖是因为我还没有在这个问题上看到与 FLOAT 类型相关的post。

No validator could be found for constraint 'javax.validation.constraints.Size' validating type 'java.lang.Float'. Check configuration for 'numIngredient'

如何更改约束以应用 FLOAT 类型?

@Data
@Entity
@Table(name = "pantry")
public class Pantry {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "userID", nullable = false)
    private Long userID;

    @Column(name = "ingredients_in_pantry", nullable = true)
    private String ingredientID;

    @NotNull
    @Column(name = "number_of_ingredients", nullable = true)
    private Float numIngredient;

    //description of pantry (home, office, kitchen, grandmas, etc.)
    @Column(name = "description", nullable = true)
    private String description;

}

来自 javadoc - @Size 支持 CharSequence、Collections、Maps、Arrays。数字类型(@Min@Max 等)的注释不支持双精度和浮点数,因为舍入错误,引用 javadoc - Note that double and float are not supported due to rounding errors (some providers might provide some approximative support). 根据您的提供者,它们可能有效,也可能不会。

您的选择是:

  1. 使用 BigDecimal - 验证数字的注释支持它。
  2. 为 double 和 float 编写您自己的自定义注释和验证器 - 如果您不知道如何使用,您可以使用这个 guide