When using @ManyToOne in JPA, such as:
@ManyToOne(cascade = CascadeType.ALL)
private Project project;
JPA automatically generates a foreign key column, but this can cause naming issues and confusion. Here's why you should explicitly define the foreign key using @JoinColumn:
If you don’t specify @JoinColumn, JPA automatically creates a column based on the field name, usually in the format:
project_id (because the field is private Project project).
But depending on the naming strategy of your database (e.g., Hibernate defaults), the column name might be:
project_idprojectIdfk_project (in some cases)If you explicitly define the foreign key, you ensure consistency across different databases.
✅ Better: Explicit Foreign Key Name
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "project_id", nullable = false)
private Project project;
Now it's clear:
project_id.nullable = false ensures that a DamageReport must always be linked to a Project.Imagine another @ManyToOne in the same entity, like: