猿问

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

应用程序和历史有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)

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


潇湘沐
浏览 214回答 2
2回答

慕容708150

改变你的@JoinColumn(name = "appId")到@JoinColumn(name = "app_id")这应该有效。

明月笑刀无情

问题是:您使用的是 MySQL 数据库,但 JPA 使用的方言是针对 PostgreSQL 的:spring:&nbsp;&nbsp; main:&nbsp;&nbsp; &nbsp; banner-mode: "off"&nbsp; datasource:&nbsp;&nbsp; &nbsp; url: jdbc:mysql://localhost:3306/cifi3?useSSL=false&allowPublicKeyRetrieval=true&nbsp; &nbsp; username: tester&nbsp; &nbsp; password: tester&nbsp; jpa:&nbsp;&nbsp; &nbsp; database-platform: org.hibernate.dialect.PostgreSQLDialect&nbsp; &nbsp; show_sql: true&nbsp; &nbsp; hibernate:&nbsp; &nbsp; &nbsp; ddl-auto: create-drop&nbsp; &nbsp; &nbsp; format_sql: true&nbsp; data:&nbsp; &nbsp; rest:&nbsp; &nbsp; &nbsp; basePath: /repo我建议你改变database-platform: org.hibernate.dialect.PostgreSQLDialect的database-platform: org.hibernate.dialect.MySQLDialect
随时随地看视频慕课网APP

相关分类

Java
我要回答