为什么 Jersey 要求我在我的项目中包含一个 bean 验证依赖项?

Why is Jersey requiring me to include a bean validation dependency in my project?

编辑:我正在使用 Jersey 2.22 和 Hibernate 4.1.4。

根据文档:

Bean Validation support in Jersey is provided as an extension module and needs to be mentioned explicitly in your pom.xml file (in case of using Maven)

据我了解,这不是必需的。但是,我在我的项目中也使用了 Hibernate,这可能是一个很大的因素。

有趣的是,我没有在我的 Hibernate 中使用 bean 验证,一切都是在 XML 中配置的老派(映射、持久性、会话工厂等)。

每当我包含来自 Jersey 包的 validation-api-1.1.0-Final.jar 作为我的依赖项的一部分时,就会出现此错误 org.hibernate.HibernateException: Error applying BeanValidation relational constraints

我所做的临时修复是在我的 Hibernate 配置中禁用 javax.persistence.validation.mode,一切正常。但问题是,我不想再触及我的配置,因为这个 Hibernate 项目在我所有的项目中都使用,我担心这个小的改变可能会产生巨大的影响——我猜是偏执狂。

所以我有两个问题:

  1. 为什么 Jersey 要求我包含 bean 验证依赖项? (从某种意义上说,如果我没有,我的应用程序将继续抛出异常)
  2. 看到我不使用 Hibernate 的 bean 验证但打算在 Jersey 中使用 bean 验证,我最好禁用 javax.persistence.validation.mode 吗?或者最好只包含一个 bean 验证 jar?

Why is Jersey requiring me to include a bean validation dependency? (requiring in the sense that if I don't have one, my app will keep throwing an exception)

我不知道为什么需要它。如果 Bean Validation 确实是可选的,那么也不应该依赖于 Bean Validation API。这可能需要在 Jersey 代码中使用一些反射。在这种情况下,也许可选意味着您不需要实际的 Bean 验证实现。如果您可以 post 删除 Bean 验证 API.

时获得的异常类型,将会有所帮助

Seeing that I don't use bean validations for Hibernate but intend to use bean validations in Jersey, am I better off disabling javax.persistence.validation.mode? or will it be best to just include a bean validation jar?

Bean Validation 与 JPA 集成,这意味着如果您通过 EntityManager 使用 Hibernate ORM,则在 class 路径上检测到 Bean Validation 时将启用它。检测是通过 Bean Validation API jar 中的 class 进行的。因此,因此,如果您添加 Bean Validation API jar,您将启用 Bean Validation(即使在您还添加 Bean Validation 提供程序(如 Hibernate Validator)之前也会有例外)。在 class 路径上有 Bean 验证 API 的情况下,禁用基于 JPA 的验证的方法确实是通过 javax.persistence.validation.mode 属性。

因此,如果您想使用 Bean Validation 在 REST 级别进行验证,您将需要 Bean Validation API + 一个实现(例如 Hibernate Validator)。一旦你在 class 路径上有了这两件事并且你不想进行基于 JPA 生命周期的验证,你将需要将 javax.persistence.validation.mode 设置为 none也是。