【问题标题】:Is there a way to load an entity into an instance of derived class?有没有办法将实体加载到派生类的实例中?
【发布时间】:2011-09-16 09:43:52
【问题描述】:

我有一个实体和从该实体派生的专用类。 有什么方法(在 JPA 或 spring 中有些棘手)让 JPA 创建派生类的实例而不是实体类?

否则我需要为每个派生类创建“复制构造函数”。或者用看起来很笨重的代表替换继承。

【问题讨论】:

    标签: java spring jpa


    【解决方案1】:
    • 如果您的实体有许多应以不同方式存储在数据库中的子类,您可以使用 JPA 继承支持(@Inheritance 等)。

    • 如果您的实体只有一个子类应该始终用来代替该实体,您可以将该子类注释为@Entity,并将实体注释为@MappedSuperclass

    • 如果您想在不修改实体的情况下实现前面的案例,您可以使用提供商特定的解决方案。例如,在 Hibernate 中,您可以注册一个自定义 Interceptor 并覆盖其 instantiate() 方法。

    【讨论】:

    • 谢谢,您的第二个选项很好,但我需要(由于缓存要求)派生类中不应保留的可序列化字段。
    • @stacker:可以将这些字段标记为@Transient,不影响序列化。
    • 大声笑,似乎我混淆了瞬态注释和瞬态关键字。
    【解决方案2】:

    如果您只想要实体的属性子集并且不想更改实体,那么我建议使用摘要样式查询。

    @Entity
    @Table(name="test_entity")
    public class TestEntity extends BaseDomainObject<Long> {
    
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        @Column(name = "name")
        private String name;
    
    
        public Long getId() {
            return id;
        }
    
    
        public void setId(Long id) {
            this.id = id;
        }
    
    
        public String getName() {
            return name;
        }
    
    
        public void setName(String name) {
            this.name = name;
        }
    }
    
    public class TestSummary {
    
        private final Long id;
    
        private final String name;
    
        public TestSummary(Long id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
    
        public Long getId() {
            return id;
        }
    
    
        public String getName() {
            return name;
        }
    }
    

    然后你可以使用这样的查询:

    select new TestSummary(te.id, te.name) from TestEntity te
    

    JPA 将生成一个只加载您想要的字段的快速查询。我在显示实体列表时一直使用它。

    【讨论】:

      【解决方案3】:

      我现在使用 lomboks delegate 注释解决了它。

      @Entity
      public class MyEntity {
         ...
      }
      
      public class MyBusinessObject {
         @Delegate
         private MyEntity entity;
      
         // other non persistent stuff
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-31
        • 1970-01-01
        • 2021-11-16
        • 2014-03-22
        • 1970-01-01
        • 2016-09-12
        • 2022-06-21
        • 2011-12-22
        • 1970-01-01
        相关资源
        最近更新 更多