When to use @Embedded and @Embeddable?

会有一股神秘感。 提交于 2019-12-10 12:57:35

问题


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?


回答1:


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




回答2:


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.




回答3:


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;
}



回答4:


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.



来源:https://stackoverflow.com/questions/35174981/when-to-use-embedded-and-embeddable

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