Hibernate生成错误的主键

问题描述

我有一个休眠实体。

@AllArgsConstructor @NoArgsConstructor @Getter
@Entity
@Table(name = "app_category_link",schema = "mariott_application")
public class AppCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "app_category_link_id")
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "app_id")
    private App app;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id")
    private Category category;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id_who_added")
    private User userWhoAdded;

    @Column(name = "date_add")
    private zoneddatetime dateAdded;
}

我有一个@DataJpaTest生成了这样的DDL。令人惊讶的是,它产生了意外的主键。

create table mariott_application.app_category_link
(
    app_category_link_id int8      not null,date_add             timestamp,app_id               bigserial not null,category_id          int8      not null,user_id_who_added    int8,primary key (app_id,category_id)     -- wrong
)

为什么Hibernate生成错误的主键?

解决方法

当您多次使用表名时可能会发生这种情况同样在 keycloakService.findUserByEmailOrUsername( user.getKeycloakUsername() ) .ifPresent( userRepresentation -> { CredentialRepresentation credential = new CredentialRepresentation(); credential.setType( CredentialRepresentation.PASSWORD ); credential.setValue( userDTO.getPassword() ); credential.setTemporary( false ); userRepresentation.setCredentials( Collections.singletonList( credential ) ); } ); / @JoinTable中。始终将现有实体用作反向@CollectionTable,而不是定义@OneToMany关联,以避免出现此问题。