I want to write the following process:
- Register a record in Table A (primary key is ‘hoge’)
- Register a record in Table B (set ‘hoge’ as the foreign key)
When inserting into a database, it’s possible to generate IDs (sequential or UUID) on the database side.
-
Method A: Generate IDs in the program and register them in the database.
- Generate the ID (‘hoge’) in the program.
- Register the record in Table A (set ‘hoge’ as the primary key).
- Register the record in Table B (set ‘hoge’ as the foreign key).
This feels natural to me.
-
Method B: Let the database generate IDs.
- Register a record in Table A (with ‘hoge’ as the primary key).
- Retrieve the primary key ‘hoge’ from Table A.
- Register a record in Table B (set ‘hoge’ obtained in step 2 as the foreign key).
This results in extra database communication to retrieve the primary key ‘hoge’.
I would like to hear your opinions (I prefer Method A).
carfun_engineer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.