Hibernate + JPA 找不到 @ElementCollection 表的列

问题描述

我正在尝试添加 @ElementCollection,但在设置后找不到该列,因此我经常收到错误消息。我使用 Spring + flyway 进行设置。一切都发生在公共架构

这是我的大对象:

@Entity
@Table(name = "my_big_table")
MyBigObject{

   @Id
   @Column(name=COL_ID)
   @GeneratedValue(generator="gen_name")
   @GenericGenerator(
            name = "gen_name",strategy = "seq_name"
        )
   @AttributeAccessor(CommonConstants.HIBERNATE_ACCESS_PROPERTY)
   private long id;
    ...
    ...
        @ElementCollection(fetch = FetchType.EAGER)
        @CollectionTable(
            name = "my_small_table",joinColumns = @JoinColumn(name = "big_object_id")
        )
    private List<MySmallObject> mySmallObjects;
}

这是我嵌入的对象:

@Embeddable
public class MySmallObject {

    @Column(name = "small_object_type")
    private String smallObjectType;
}

然后除了现有的 my_big_table 表,我使用 flyway 添加 my_small_table

create table if not exists my_small_table
(
    big_object_id      bigint not null,small_object_type     varchar(64) not null
);

alter table my_small_table
      add constraint FK_my_small_table
      foreign key (big_object_id)
      references my_big_table (id);

在此之后,my_small_table 成功创建,但无法找到 MyBigObject 的任何实例,因为它在 my_small_table 中查找不存在的列。如您所见,它不理解列名应该使用下划线。

Big error trace ands with the following message:
Caused by: org.postgresql.util.PsqlException: ERROR: column mysmalltab0_.smallobjecttype does 
not exist
09:17:24.994 INFO  - STDOUT:   Hint: Perhaps you meant to reference the column "mysmalltab0_.smallobjecttype".

你知道我会忘记什么吗?我也用于两个类的 lombok 注释会破坏图片吗?

解决方法

正如 documentation 中所述:

默认情况下,@Id 注释的位置给出了默认访问策略。当放置在一个字段上时,Hibernate 将承担基于字段的访问。当放置在标识符 getter 上时,Hibernate 将使用基于属性的访问。

但是 @AttributeAccessor 的使用导致保存 @Id 的字段的访问策略发生变化,因此您的 @Column(name = "small_object_type") 注释被忽略了。您可以尝试将其放在适当的 getter 上,它应该可以工作。但最好不要混淆实体字段的访问策略。