问题
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;
回答1:
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 owningEntity
. - an
Entity
cannot be embedded, because eachEntity
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.
回答2:
Why not just create the entity that you want, and in that entity, embed C as well. That way you have C in both classes, one as embedded and another as embedded of the new entity.
@Embeddable
public class Contact {
private String firstname;
private String lastname;
// getters and setters removed.
}
and here is your embedding class:
@Entity
public class Student {
@Embedded
private Contact contact;
}
and here is the new entity that embeds contact also
@Entity
public class FirmContact {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int contactId;
@Embedded
private Contact contact;
}
And finally the class that insists the contact must be an entity:
@Entity
public class Business {
@OneToOne(cascade=CascadeType.ALL)
private FirmContact contacts;
}
It'll just be a couple of extra steps in java to populate the object, but it should do the mapping you want. I hope this helps.
来源:https://stackoverflow.com/questions/28949853/is-it-possible-to-force-hibernate-to-embed-an-entity