Search code examples
mysqlforeign-keysone-to-manymany-to-one

Error executing DDL "alter table add constraint foreign key () references (id)" via JDBC Statement


Error executing DDL "alter table child add constraint foreign key (parent_id) references (id)" via JDBC Statement caused by Failed to add the foreign key constraint. Missing index for constraint '' in the referenced table ''

caused by Failed to add the foreign key constraint. Missing index for constraint '' in the referenced table ''

Below are my entity class

@Entity
@Table(name = "parent")
public class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "parent", cascade = { CascadeType.PERSIST,
            CascadeType.MERGE }, fetch = FetchType.EAGER, orphanRemoval = true)
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Child> child = new HashSet<>();

Below is another entity class for manytoOneampping

@Entity
@Table(name = "child")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Child implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    @JsonIgnoreProperties("child")
    private Parent parent;

Solution

  • I noticed in db, duplicates tables were being created so that's why i was getting that error

    Adding below annotation solved my problem :

    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)