Mikhail
Mikhail

Reputation: 769

Spring JDBC. Insert record with one to many relationship

I'm started to study Spring JDBC, without hibernate or anything similar. I'm a bit confused that I still can't find how to perform insert for entity with one to many relationship. For example, I have two tables - TableA and TableB. Table A contains tableA_id, name. TableB contains tableB_id, value, tableA_id. So basically tableA entity contains a list of tableB records. Could you please give me an example how the tableA's DAO save method will look like? I have a few ideas, like insert tableA record, get it's id, and then insert all the tableB records in a loop. But I'm not sure that this is a right idea.

Upvotes: 0

Views: 2596

Answers (1)

What you described is basically what you have to do.

  1. insert tableA
  2. get As id
  3. insert all Bs in a loop

Because this concerns two daos, you should make a service, that delegates to the daos. You should also consider to make that service method transactional, otherwise you may end up with semi persisted objects when the system crashes..

JPA (Hibernate) can do all this automatically for you.

Upvotes: 4

Related Questions