Is it possible to annotate a class as @Embeddable
or a property as @Embedded
?
Sample code:
@Embeddable
class A{
...
}
cla
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.)
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.
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;
}
I guess if you annotate class as @Embeddable
you don't need to annotate field as @Embedded
. Also, if you annotate class as @Embeddable
and you want to use it as primary key, you can use @Id
only, but if it is not annotated as @Embeddable
, you have to use @EmbeddedId
on field to work as primary key.