jpa引用外部表而不是JoinColumn中的外部列

时间:2018-11-05 08:10:16

标签: java hibernate spring-boot jpa spring-data-jpa

App History OneToMany

@Entity
@Table(name = "app")
@SuppressWarnings("serial")
public class App implements Serializable {
    @Id     @Column(name = "app_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long appId;
    private String name;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "app", cascade = CascadeType.PERSIST)
    private Set<History> history = new HashSet<>();
    //get.set
}

@Entity
@Table(name = "app_history")
@SuppressWarnings("serial")
public class History implements Serializable {
    @Id
    @Column(name = "history_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long historyId;
    @JoinColumn(name = "appId")
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REFRESH)
    private App app;
    //get.set
}

正在查看日志:

create table app (app_id int8 not null, name varchar(255), primary key (app_id))

create table app_history (history_id int8 not null, app_id int8, primary key (history_id))

alter table app_history add constraint FKeuk3km6r7oklj5xc1ecwvxmkm foreign key (app_id) 
references app

期望上面的行是

alter table app_history add constraint FKeuk3km6r7oklj5xc1ecwvxmkm foreign key (app_id) 
references app (app_id)

那么,当jpa尝试创建表时,为什么(app_id)丢失了?

注意:我在

  • mysql v8.0.12
  • mysql-connector-java v8.0.13
  • spring-boot v2.1.0.RELEASE
  • 完整代码here
  • 日志为here

2 个答案:

答案 0 :(得分:2)

更改您的

@JoinColumn(name = "appId")

@JoinColumn(name = "app_id")

这应该有效。

答案 1 :(得分:1)

这是问题所在:您使用的是MySQL数据库,但JPA使用的方言适用于PostgreSQL:

ConcurrentHashMap

我建议您在spring: main: banner-mode: "off" datasource: url: jdbc:mysql://localhost:3306/cifi3?useSSL=false&allowPublicKeyRetrieval=true username: tester password: tester jpa: database-platform: org.hibernate.dialect.PostgreSQLDialect show_sql: true hibernate: ddl-auto: create-drop format_sql: true data: rest: basePath: /repo 中更改database-platform: org.hibernate.dialect.PostgreSQLDialect