Search code examples
javajpahibernate-mapping

How to make JPA interpret List<Element> (size only 0 or 1) as single Element


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 ?


Solution

  • 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;
    
    }