When to use @Embedded and @Embeddable?

后端 未结 4 1005
别跟我提以往
别跟我提以往 2021-01-18 01:10

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

Sample code:

@Embeddable
class A{
...
}

cla         


        
4条回答
  •  孤独总比滥情好
    2021-01-18 01:36

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

提交回复
热议问题