【问题标题】:JPA: How can an @Embeddable object get a reference back to its owner, but the @Embeddable is in a lazy collection?JPA:@Embeddable 对象如何将引用返回给其所有者,但 @Embeddable 位于惰性集合中?
【发布时间】:2017-06-09 11:17:32
【问题描述】:

我知道,如果您想从 @Embeddable 引用回其父级,您可以在 setter 中“手动”设置父级,并按照this answer 中的说明将@Access(AccessType.PROPERTY) 用于此嵌入字段,但如果这样怎么办嵌入的元素被映射到一个集合中,该集合是延迟加载的?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    实际上不确定这是否是一个问题,如果不是“手动”从 @embeddable 引用回其父级,一切都很好。

    @CollectionTable.JoinColumns()用于设置引用实体主表的集合表的外键列,这意味着一旦设置了这个可选属性,就没有必要“手动”从@embeddable引用回来它的父级。

    以你的案例为例:

    @Entity
    public class Image {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
    ....
    
        @ElementCollection(fetch = FetchType.LAZY)
        @CollectionTable(name = "COMPUTERS", joinColumns = @JoinColumn(name = "ID_IMAGE"))
        private List<Computer> computers;
    }
    
    @Embeddable
    public class Computer {
    
        @Column
        private String ipAddress;
    
        *****//This idImage field is not necessary
        @Column(name = "ID_IMAGE", insertable = false, updatable = false)
            private Long idImage;*****
    
    }
    

    一旦注释掉字段idImage及其@Column注解,生成的SQL是:

    create table IMAGES (
               id bigint not null,
                Name_Image varchar(255),
                primary key (id)
            )
    
    create table COMPUTERS (
           ID_IMAGE bigint not null,
            ipAddress varchar(255)
        )
    
     alter table COMPUTERS
       add constraint FKl1ucm93ttye8p8i9s5cgrurh
       foreign key (ID_IMAGE)
       references IMAGES
    

    如果在embeddable类中“手动”声明join列,虽然DDL相同,但是embeddable对象会多出一个字段“imageId”,这会导致执行INSERT操作时JDBC调用参数超出索引.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 2014-08-24
      • 2019-12-02
      相关资源
      最近更新 更多