membersound
membersound

Reputation: 86747

How to trigger foreign key relation without adding a reference @Entity in hibernate?

The following relationship creates a foreign key mapping

@Entity
public class Department {
   @Id
   private String name;

   //some more fields
}

@Entity
public class Employee {
   @Id
   private long id;

   private String name;
   private String designation;

   @ManyToOne
   @JoinColumn(name = "fk_department_id", foreignKey = @ForeignKey(name="fk_department"))
   private Department department;
}

generates:

...CONSTRAINT fk_department FOREIGN KEY (fk_department_id) REFERENCES department (name)

Question: how can I trigger this constraint creation in hibernate without having to create the Department entity?

Eg just adding the foreign key @Id field without an explicit entity reference. But still trigger the fk on initial creation. The following is of course invalid:

   @ManyToOne
   @JoinColumn(name = "fk_department_id", foreignKey = @ForeignKey(name="fk_department"))
   private String department;

You get the intention. Is that possible?

(sidenote: I'm not interested in creating that foreign key link by startup ddl/sql statements).

Upvotes: 0

Views: 661

Answers (1)

Kayaman
Kayaman

Reputation: 73558

You'll have to drop @ManyToOne at least, since that's for entities.

The following should work by overriding the column definition to include the foreign key while creating it

@Column(name = "department_id", columnDefinition = "VARCHAR(255), foreign key (department_id) REFERENCES department(name)")
private String department;

Now there's only a column and a constraint defined, but no relation (as far as Hibernate knows) defined between entities.

Essentially copied from Hibernate and JPA: how to make a foreign key constraint on a String but that was darn hard to find, so I'm not just going to close this as a duplicate! ;)

Upvotes: 3

Related Questions