Is it possible to force Hibernate to embed an Entity?

瘦欲@ 提交于 2020-01-04 05:14:25

问题


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 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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!