I'm trying to impose a @Oneto7 association. I'd have imagined an attribute that specifies the target many value, but have found none. If there is no such attribute, how else, in JPA/EclipseLink would one achieve it?
How to specify the cardinality of a @OneToMany in EclipseLink/JPA
Asked Answered
You could use the Bean Validation API (JSR-303) - Hibernate Validator being the RI - and add a Size
constraint on your collection:
@Size(min = 7, max = 7) protected Set<Foo> foos = new HashSet<Foo>();
If you're using JPA 1.0, have a look at this previous answer to see how to use Bean Validation with JPA 1.0.
That's a solution. However, I'd like to keep using EclipseLink, any solution there? –
Quinquefid
@Quinquefid Huh? There is nothing in my answer that suggests to drop EclipseLink. My suggestion is to use the Bean Validation API that you use beside the JPA provider. Hibernate Validator is an implementation of this API, it's not an alternative to EclipseLink, you use it beside EclipseLink. –
Stralka
In the example code provided in your link, I read <provider>org.hibernate.ejb.HibernatePersistence</provider>, which mislead me. –
Quinquefid
Please answer my related question: stackoverflow.com/questions/2707683/… –
Quinquefid
In the code of the answer the annotation is used as: @Size(min = 5, max = 20) private String author; What does it mean, when author is at most one here? Anyway, the code also uses Validation.buildDefaultValidatorFactory().getValidator().validate(...), which raises this question: Is @Size not going to be translated in DDL SQL? Could you post a SSCCE? I'm trying with the example posted here, vogella.de/articles/JavaPersistenceAPI/article.html, to make the family max size 7. –
Quinquefid
@Quinquefid
@Size
on a String
would constraint the size of the String
(and the max would also be reflected in the DDL). On a Collection
, it constraints the size
of the Collection
which is what you're asking for (but won't be reflected in the DDL, how could this be). Then, I'm not sure of what code you're referring to, the line you're mentioning is not part of the link I posted that covers both JPA 2.0 and JPA 1.0 (follow it, it provides everything you need). What do you have so far? What part is not working? I tested my suggestion with a JPA 2.0 provider, it just works. –
Stralka You may use the Oval library and set e.g.:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "whatevery")
@Size(max = 30)
private List<SuperDocument> documents;
Here is the documentation for further validations of Oval: http://oval.sourceforge.net/userguide.html#api-documentation
© 2022 - 2024 — McMap. All rights reserved.