Ask Your Question
0

How can a foreign key constraint be implemented on a table using Spring Boot JPA when the constraint references the same table?

asked 2022-01-11 11:00:00 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-27 02:00:00 +0000

lakamha gravatar image

To implement a foreign key constraint on a table using Spring Boot JPA when the constraint references the same table, you can follow these steps:

  1. Define the entity class for the table with the foreign key reference. In the entity class, you need to define a field that represents the foreign key column.

  2. Annotate the foreign key field with the @ManyToOne annotation, which indicates that this field represents a many-to-one relationship with another entity (in this case, the same entity).

  3. In the @ManyToOne annotation, set the targetEntity attribute to the same class as the entity being defined.

  4. In the @JoinColumn annotation, set the name attribute to the name of the foreign key column in the current table.

  5. Set the referencedColumnName attribute to the name of the primary key column in the referenced table (the same table in this case).

  6. Finally, add the @OnDelete annotation to specify the action to be taken when the referenced row in the same table is deleted. For example, @OnDelete(action = OnDeleteAction.CASCADE) specifies that the row with the foreign key should also be deleted.

Example code:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToOne(targetEntity = Employee.class)
    @JoinColumn(name = "manager_id", referencedColumnName = "id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Employee manager;

    // getters and setters
}

In this example, the Employee entity has a many-to-one relationship with itself through the manager field, which represents the foreign key column. The @JoinColumn annotation specifies the name of the foreign key column, which is "manager_id", and the referencedColumnName attribute specifies the name of the primary key column in the same table, which is "id". The @OnDelete annotation specifies that when a manager Employee is deleted, all employees under that manager will also be deleted due to the CASCADE action.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-11 11:00:00 +0000

Seen: 14 times

Last updated: Mar 27 '23