Hibernate不创建联接表

时间:2018-10-20 22:27:56

标签: mysql spring hibernate spring-data-jpa

我遇到的问题以前从未发生过。我有ManyToMany关系,并且Hibernate没有创建联接表。它仅创建实体表。我在MySQL中使用SpringDataJpa。

医生实体:

Entity
@Table(name = "doctors")
public class Doctor {
  @Id
  @Size(min = 11, max = 11)
  @NotNull
  private String pesel;

  @NotNull
  private String firstName;

  @NotNull
  private String lastName;

  private Long salary;

  @NotNull
  private String speciality;

  @OneToOne
  private Doctor supervisor;

  @ManyToMany
  @JoinTable(name = "doctors_treatments",
          joinColumns = @JoinColumn(name = "pesel", referencedColumnName = "pesel"),
          inverseJoinColumns = @JoinColumn(name = "treatment_id", referencedColumnName = "id"))
  private Set<Treatment> treatments;
}

治疗实体:

@Table(name = "treatments")
public class Treatment {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  @NotNull
  private String name;

  private Long cost;

  @ManyToMany(mappedBy = "treatments")
  private Set<Doctor> doctors; 
}

application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:33061/sys

StackTrace:

  org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
    ...
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'sys.doctors_treatments' doesn't exist

任何想法可能是什么原因?

1 个答案:

答案 0 :(得分:1)

事实证明,由于 Doctor 主键扩展了允许的大小,因此Hibernate没有创建联接表。但是,它只能创建 Doctors 表。因此,为了修复它,我必须限制id的大小。我已经这样更改了医生 id:

?- visit(brussels, [minsk, zagreb, tirana], L).
L = [(minsk, 1603870),  (zagreb, 1023569),  (tirana, 1589189)] .

现在,Hibernate可以创建联接表。