So I come from Spring Boot background and I was really impressed how Spring @Transactional annotation just worked seamlessly along with Hibernate.
I am working on a Dropwizard application now that is using Jdbi3. And I have found a similar @Transaction annotation that works quite the same way as Spring but with some pre conditions.
Spring
So according to Spring Guidelines, Repository and Controller are the two interfaces which communicates to the database and HTTP requests respectively, Service Layer was the place where all the business logic belongs.
There was always a case where a single method in service does CRUD operations using multiple repositories. Thus it makes so much sense to make the service method annotate with @Transational.
Jdbi with Dropwizard
So correct me if I am wrong. Here in Jdbi the Repository becomes Dao, Controller becomes Resource and Service remains Service. Maybe different people use different layer architecture, but let's just assume this is the case where my problem lies in.
Problem statement
I wish to achieve the same Transaction Handling in Jdbi as in Spring ideologically because it makes much more sense to me without adding any extra layer. Here's I'll throw some code, what I wish to achieve:
Dao1.kt
interface Dao1{
@SqlUpdate("INSERT INTO table1...")
fun insert() : Int
}
Dao2.kt
interface Dao2{
@SqlUpdate("INSERT INTO table2...")
fun insert() : Int
}
Service.kt
class Service{
@Transaction
fun save() {
Dao1 =Dao1() //What should be expected way to instantiate
Dao2 =Dao2() //What should be expected way to instantiate
dao1.insert()
dao2.insert()
}
}
Few points to note
I am aware that
onDemandcan only be used onabstractclass or interface, thus I cannot instantiateServiceusingonDemand. Also i cannot make myServiceabstract.Few articles suggests to make an abstract
Repositoryand useTransactionthere. But as per my thought when I think of repository, I see it has a one-to-one mapping with theentity/table. Or maybe related entities. So if I want to updatemovieandusertable in the same service method, putting these two transaction statement under a method in someXRepositorysounds very absurd to me. Its a part of business logic and should reside inService.I think I can use
jdbi.inTransactionandjdbi.useTransaction. But in that case I have to attach each and everyDaomanually. Is there a better way to do that?
Thanks