Search code examples
javahibernatejpaormhibernate-mapping

Is it possible to force Hibernate to embed an Entity?


In my use-case, I would like to @Embedded a class C in an entity.

Another entity refers to C with @OneToMany association and therefore C is annotated with @Entity.

I am aware that this seems like bad design, yet I believe that it makes perfect sense in my case.

Is it possible to force Hibernate to embed an Entity? If I try it, Hibernate complains about a missing setter for the id property of C.

I think the problem comes from this:

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;

Solution

  • Hibernate doesn't allow you to treat an Embeddable as an Entity or to embed an Entity. According to Hibernate types:

    • an Embeddable, doesn't have an identifier, since it's state is part of an owning Entity.
    • an Entity cannot be embedded, because each Entity has a distinct life-cycle.

    Since another class already has a @OneToMany association to class C, it's obvious you cannot turn it into an Embeddable.

    More, a bidirectional @OneToMany association will perform better than an embeddable collection.

    What you can do, is to use it as a @OneToOne association in the entity where you wanted to embed the C entity. You can make that target entity be the owning side of the association so that the C association is bound to the target entity life-cycle.