0

As the title says I want to create triggers to create records in other tables when data is added in the primary table. For example, when a user registers, I want records in user_friends with some default value.

Initially I thought to handle in the service layer like this.

repositoryA.save(entityA);
repositoryB.save(entityA);

But this method creates two different db sessions and I want to keep the number of sessions / calls to a minimum. Would also like to avoid native SQL or tweaking the db directly.

Zàf Mohammed
  • 127
  • 1
  • 9
  • If this code is in a single service method with `@Transactional` it is a single session. If you want default values, then make a proper mapping in JPA and fill the defaults in your java code. – M. Deinum Nov 04 '19 at 11:12
  • Wow. This is quite the revelation to me. – Zàf Mohammed Nov 05 '19 at 03:41

1 Answers1

0

When you have a relation between the tables you can persist the data in one save action. See also JPA Persist parent and child with one to many relationship

FredvN
  • 504
  • 1
  • 3
  • 14
  • Interesting. In my case the mapping/relationship is owned by the child. I tried to avoid having cascades but I'll reconsider. This + using @Transactional might solve my issue. – Zàf Mohammed Nov 05 '19 at 03:44