2

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?

simpatico
  • 10,709
  • 20
  • 81
  • 126

2 Answers2

2

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.

Community
  • 1
  • 1
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • That's a solution. However, I'd like to keep using EclipseLink, any solution there? – simpatico Apr 24 '10 at 21:09
  • @simpatico 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. – Pascal Thivent Apr 24 '10 at 21:47
  • In the example code provided in your link, I read org.hibernate.ejb.HibernatePersistence, which mislead me. – simpatico Apr 24 '10 at 22:04
  • Please answer my related question: http://stackoverflow.com/questions/2707683/how-do-i-import-javax-validation-into-my-java-se-project – simpatico Apr 25 '10 at 08:54
  • 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, http://www.vogella.de/articles/JavaPersistenceAPI/article.html, to make the family max size 7. – simpatico Apr 25 '10 at 09:36
  • @simpatico `@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. – Pascal Thivent Apr 25 '10 at 17:42
0

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

feder
  • 1,775
  • 5
  • 25
  • 36