Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Embedded in @Embeddable class

Can I use @Embedded in @Embeddable class in hibernate.

Example : A is an element collection in a diffirent class.

@Embeddable
class A {

    @Embedded
    B b;
}

@Embeddable
class B {

    @Embedded
    C c;
}


@Embeddable
class C {

    @Embedded
    D D;
}

@Embeddable
class D {



}

Is something of this kind valid in hibernate ? The third level of nesting.

like image 1000
Sandeep Rao Avatar asked Mar 01 '13 23:03

Sandeep Rao


People also ask

When we use @ID or @embedded on the field?

We represent a composite primary key in Spring Data by using the @Embeddable annotation on a class. This key is then embedded in the table's corresponding entity class as the composite primary key by using the @EmbeddedId annotation on a field of the @Embeddable type.

What is the use of @embedded in spring boot?

JPA provides the @Embeddable annotation to declare that a class will be embedded by other entities.

What is @embedded annotation in Java?

Annotation Type Embeddable. Defines a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.

Can an embeddable class contain relationships with other entities?

Embeddable classes may also contain relationships to other entities or collections of entities. If the embeddable class has such a relationship, the relationship is from the target entity or collection of entities to the entity that owns the embeddable class.


2 Answers

Yes, it is valid in Hibernate to nest @Embedded objects.

Directly from the docs (http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e714) :

@Entity
public class Person {

    @Embedded
    Address homeAddress;
}          

@Embeddable
public class Address {

    @Embedded
    Country nationality;
}            

@Embeddable
public class Country {
    ...
}    

(Removed extra code to highlight nesting @Embedded)

like image 124
John Ericksen Avatar answered Oct 05 '22 22:10

John Ericksen


As mentioned by johncarl, it is possible. In order to rename nested attributes you have to specify the entire chain, using '.' as separator. For example, if class D has an attribute foo, then in class A you would need to rename it as such:

@Embedded
@AttributeOverride(name = "c.D.foo", column = @Column(name = "bar"))
B b;
like image 37
Thiago Chaves Avatar answered Oct 06 '22 00:10

Thiago Chaves