0
class Entity {
    private InnnerEntity innerEntity;
}

I had above structure in JPA previously, but now I have to change it to collection like:

class Entity {
    private List<InnnerEntity> innerEntity;
}

And this list will contain only 1 or 0 elements. So I need to make JPA work with that structure exactly as it was before. I mean to still have mapping one to one or in other case have it as an embedded entity. Is that even possible ?

Yaroslav Kovbas
  • 430
  • 4
  • 7
  • why not keeping is as a single element and use null – Karim Dec 27 '19 at 09:56
  • Does this answer your question? [Is it possible to limit the size of a @OneToMany collection with Hibernate or JPA Annotations?](https://stackoverflow.com/questions/26328187/is-it-possible-to-limit-the-size-of-a-onetomany-collection-with-hibernate-or-jp) – mentallurg Dec 27 '19 at 09:59
  • @Karim we have tricky case where we use 3rd party library and it needs to have it as a collection. And on another end we have production data which operates through these JPA entities. – Yaroslav Kovbas Dec 27 '19 at 10:11
  • @mentallurg no, unfortunately it doesn't – Yaroslav Kovbas Dec 27 '19 at 10:12
  • @YaroslavKovbas: But that is exactly what yre you trying to do: Yoiu want to limit the size of relation to max. 1 element. That post explains why you cannot do that. – mentallurg Dec 27 '19 at 10:13
  • Well, this is not possible with JPA, but what you can do is set a Validation trigger in the database, what kind of database you have? – Karim Dec 27 '19 at 10:19

1 Answers1

1

You can use Bean validation to limit the size of the collection to 1 but you will have to use OneToMany because OneToOne doesn't work on collections:

class Entity {

    @Size(1)
    @OneToMany
    private List<InnnerEntity> innerEntity;

}
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82