java - @Entity和@Embeddable之间的继承

标签 java database hibernate jpa

动机

我的应用程序根据表 foo 的内容向某些 Web 服务发出请求。我想记录这些请求(在数据库中)以及用于制作它们的 foo 行的值。尽管如此,由于表 foo 中的数据可能会随着时间的推移而改变,我需要记录行的确切内容(而不是它的 id)。我正在使用 Hibernate,所以我想,我可以将 foo 行嵌入表示请求的实体中。为了拥有干净的类层次结构,我想要这样的东西:

 class Foo
 {
   /*
    * Here goes some properties of Foo, which specify columns names etc.
    */
 }

 @Embeddable
 class EmbeddableFoo extends Foo
 {
   //EmbeddableFoo should have the same properties as Foo
 }

 @Entity
 class EntityFoo extends Foo
 {
   @Id
   Long getId() { //EntityFoo  has some id }
   //EntityFoo should have the same properties as Foo, except that
   //it has id
 }

问题

这不会起作用,因为EmbeddableFoo看不到Foo的属性。我可以在 Foo 上添加 @Inheritance 注释,以便 EntityFoo *看到* Foo 的属性,但它会无法解决我的问题 EmbeddableFoo

问题

有没有一种简单的(即不需要编写大量冗余代码)方法让@Embeddable和@Entity*继承同一个类?

最佳答案

你检查过注释吗@MappedSuperclass ?这可能就是您正在寻找的。

http://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html

Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

A class designated with the MappedSuperclass annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself. When applied to the subclasses the inherited mappings will apply in the context of the subclass tables. Mapping information may be overridden in such subclasses by using the AttributeOverride and AssociationOverride annotations or corresponding XML elements.

关于java - @Entity和@Embeddable之间的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597806/

相关文章:

java - 使用 Junit 5 的 RestController unsit 测试中没有名为 'entityManagerFactory' 的 bean

java - Log4j 1.x Sentry 附加器 : suppress warnings from specific sources for one appender

javascript - 如何将使用 javascript 和 ASP.NET 生成的字段中的数据发送到 Microsoft SQL?

mysql - 数据库查询中的锁

java - JPA:如何在运行时指定类对应的表名?

Java hibernate 在读取时截断 MySQL 日期时间的时间部分

mysql - Hibernate相互一对一关系

java - Mobicents JAIN SLEE 中的部署顺序

带链表的 Java 优先级队列

database - 如何构建表以快速搜索大量列