Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use @Embedded and @Embeddable?

Is it possible to annotate a class as @Embeddable or a property as @Embedded?

Sample code:

@Embeddable
class A{
...
}

class B{
...
}

@Entity
class Foo {
    A a;
    @Embedded B b;
}

When to prefer @Embedded and @Embeddable?

like image 235
Thorben Stangenberg Avatar asked Feb 03 '16 10:02

Thorben Stangenberg


3 Answers

If we have Person and Address that are two POJOs, You would not want to create another table for Address but you would want to embed the address within the person table. So Address is adding up value to the Person object but doesn't make any sense individually. In this case we may go with:

@Embeddable
public class Address{
}

@Entity
public class Person
{
    @Embedded
    private Address address;
}
like image 137
Rupesh Avatar answered Oct 24 '22 10:10

Rupesh


There are two primary uses for @Embedded/@Embeddable as far as I know:

First, and most important: Splitting up large entity classes. In the database world, a large table (one with many columns) is fine. Breaking up such a table might even make things worse, and be in collision with database design principles. In Java (or object oriented languages in general), on the other hand, a large class is a code smell. Here, we would like to split the classes, including entity classes, into smaller units. @Embedded/@Embeddable allows us to easily do this without having to split the database table.

Second, it allows for reuse of common mappings between entities. Say each table has a simple revision tracking, with two columns containing the username of the person who changed the row, and the time it happened. Then, one can make an @Embeddable entity covering these rows, and then reuse this across all entities by embedding it (rather than repeating the variables corresponding to these columns in each entity.)

like image 26
Tobb Avatar answered Oct 24 '22 12:10

Tobb


You would use @Embeddable and @Embedded together. You mark your class as @Embeddable, which indicates that this class will not exist in the DB as a separate table. Now when you use @Embedded on the field itself.

The word embeddable and embedded gives you a big clue actually.

Embeddable = This class can be embedded in a class Embedded = This class will now be embedded in your class as a field.

like image 36
johnwick0831 Avatar answered Oct 24 '22 10:10

johnwick0831