Unique constraint with JPA and Bean Validation

前端 未结 4 1923
南方客
南方客 2020-11-30 02:25

I\'d like to have a @Unique constraint with Bean Validation, but that is not provided by the standard. If I would use JPA\'s @UniqueConstraint I wo

相关标签:
4条回答
  • 2020-11-30 02:46

    More information on how to implement a @Unique and the problematic around it can be found here - http://community.jboss.org/wiki/AccessingtheHibernateSessionwithinaConstraintValidator

    0 讨论(0)
  • 2020-11-30 02:48

    You can make a validator read the JPA annotations and apply it. Here is somewhat of an example using spring validators that can be used as an idea to expand on.

    JPA JSR303 Spring Form Validation

    You can also inject (@Inject or Spring's @Autowired) your session bean in a custom validator and the container should know how to wire it up. I only know this as a Spring example:

    import javax.validation.ConstraintValidator;
    
    public class MyConstraintValidator implements ConstraintValidator {
    
    @Autowired //@Inject
    private Foo aDependency;
    
    ...
    }
    
    0 讨论(0)
  • 2020-11-30 02:53

    Well you CAN do it, but it's not trivial. The problem is: the validator requires database access to perform some queries to check, if the value you want to insert is already there or not. And this can't be really done from the validator, as it doesn't have access to the sessionFactory/session. Of course you could instantiate it (session/sessionFactory) inside the validator, but it's not a good coding practice.

    0 讨论(0)
  • 2020-11-30 02:57

    Unless you acquire a lock on a whole table, it is basically not possible to check for unicity using a SQL query (any concurrent transaction could modify data after a manual check but before the commit of the ongoing transaction). In other words, it isn't possible to implement a valid unique verification at the Java level and thus to provide a validation implementation. The only reliable way to check for unicity is while committing the transaction.

    The BV spec summarizes it like this:

    Appendix D. Java Persistence 2.0 integration

    Question: should we add @Unique that would map to @Column(unique=true)?

    @Unique cannot be tested at the Java level reliably but could generate a database unique constraint generation. @Unique is not part of the BV spec today.

    So while I agree that it would be nice to have unique (and non null) constraint violations wrapped in a Bean Validation exception, this is currently not the case.

    References

    • Bean Validation specification (JSR 303)
      • Appendix D. Java Persistence 2.0 integration
    • Question about validation and persistence constraints
    0 讨论(0)
提交回复
热议问题