Additional JPA annotations - Foreign key
This annotation is just a simplification, it allows you to combine records that are saved in the database at the same time without using a transaction. The connection is built automatically based on the annotated field. Take, for example, a case where we want to save a master and a detail record in a database that is linked by a foreign key. In this case, the unique key of the master record must be in the detail record. The unique identifier of the master record is determined only after saving (e.g. a sequence-generated value). By default, a save should be made within a transaction - first, we save the master record, then read the primary identifier from it, then save also the detail record. You can see this in the below example:
By using the ForeignKey annotation (if the save process does not require a transaction), you can replace this process with a simple save statement. Make sure that the list of records passed to the save operation always contains the master record before the detail record, otherwise we will get an error.