1 DAO+Cascade Or 2 DAO On Header-Detail Transaction

1 or 2 DAO

Suppose you have a One-To-Many relation (header-detail) on Pembelian and PembelianDetail. If you are not Indonesian then to make it easier for you Pembelian is Purchase in English.
As usual we use @OneToMany and @ManyToOne annotation in our domain class. When writing those annotation it depends on our strategy, whether we will use 1 DAO+Cascade or 2 DAO to persist the data.

relation

To better understanding my sentence here’s the code

1 DAO+Cascade

In this strategy we use just 1 DAO to persist both the header and the detail data which is Pembelian and PembelianDetail.

This DAO is called in PembelianService with declarative transaction using @Transactional annotaion.

So for you who might wondering how this strategy can save the detail data (PembelianDetail) since we didn’t create PembelianDetailDao here’s the trick. We use cascade property in @OneToMany so that every PenjualanDetail attached to Penjualan will be persisted automatically.

If we look into the generated SQL here’s what we will get

Let’s see second strategy

2 DAO

In this strategy we write 2 DAO, PembelianDao and PembelianDetailDao.

Next when we write PembelianDao we call PembelianDetailDao object inside this class.

Since we didn’t use cascade property so every PembelianDetail attached in Pembelian must be persisted manually and individually in iteration way. And here’s the @OneToMany annotation

Again, we use PembelianService to call PembelianDao. The service is the same with the one we wrote above, there is no difference

The SQL is same as well

Conclusion

So both strategy is actually the same, we can infer it from the generated SQL. The important part is both persist strategy is in one transaction. 1 Dao+Cascade is in one transaction. 2 Dao is also in one transaction.

Facebook Comments
 

Agung Setiawan

Agung Setiawan adalah software engineer di BukaLapak.com, penulis sekaligus pecinta sastra, dan pembaca buku

 
Halo, perkenalkan saya Agung Setiawan.
Saya Software Engineer di BukaLapak.
Simak pemikian saya soal dunia Software Engineering via Twitter di @agungsetiawanmu dan facebook
Blog ini saya update seminggu sekali jadi sering-sering saja mampir
Mau belajar Vim bareng saya?
Belajar ngoding dari nol menggunakan PHP

Leave a Reply

Your email address will not be published. Required fields are marked *