Spring JPA: How to force a foreign key constraint validation when using just @JoinColumn and not a full blown @ManyToOne

75 views Asked by At

For example, consider the following code, when the parent doesn't reference the children but the children can reference the parent's id. A child doesn't care about the actual parent fields like the name.

@Entity
class Parent {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column
  String name;
}

@Entity
class Child {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @Column
  String name;

  // 1. For simplicity, a child can have only one parent
  // 2. Reference just the parent id - don't care about the parent's fields
  @JoinColumn(table = "parent", referencedColumnName = "id")
  long parentId;
}

So now, when I insert a child, without first inserting a parent, I don't get any "foreign key constraint violation" or as spring defines it "DataIntegrityViolationException". Example of an insert:

repo.save(new Child("no_god?"));

Tried also foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT).

When I defined a full blown @ManyToOne(optional = false) on the child + @OneToMany on the parent, it works, but I want to use a simple id relationship - not full blown objects.

How to make the foreign key constraint work with a simple id reference definition?


1

There are 1 answers

2
phuongnq1995 On

If you only want JPA to create your DDL but don't want to mapping them, you can specify it


    @Column(columnDefintion="bigint references parent(id)")
    long parentId;

You need to specify it by your database specific SQL type and syntax for the constraint.