本文介绍了何时使用@Embedded和@Embeddable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将类注释为@Embeddable或将属性注释为@Embedded?

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

示例代码:

@Embeddable
class A{
...
}

class B{
...
}

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

何时更喜欢@Embedded@Embeddable?

推荐答案

据我所知,@Embedded/@Embeddable有两个主要用途:

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

首先,也是最重要的:拆分大型实体类.在数据库世界中,一个大表(一个有很多列的表)很好.分解这样的表甚至可能使情况变得更糟,并且与数据库设计原则相冲突.另一方面,在Java(或通常面向对象的语言)中,大类是code smell.在这里,我们希望将包括实体类在内的类拆分为较小的单元. @Embedded/@Embeddable使我们可以轻松执行此操作,而无需拆分数据库表.

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.

第二,它允许重用实体之间的公共映射.假设每个表都有一个简单的修订跟踪,其中两列包含更改行的人的用户名及其发生的时间.然后,可以制作一个@Embeddable实体来覆盖这些行,然后通过将其嵌入而在所有实体中重用(而不是在每个实体中重复与这些列相对应的变量.)

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

这篇关于何时使用@Embedded和@Embeddable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 03:41