我来自Spring Boot的背景,我对Spring如何在非接口和非抽象类中使用JDBI注解印象深刻。@Transactional
注解与Hibernate一起无缝工作.我现在正在使用一个Dropwizard应用程序,该应用程序使用了 Jdbi3
. 我也发现了一个类似的 @Transaction
注解,其工作方式与 Spring
但具备一定的前期条件。
所以根据《春秋准则》。Repository
和 Controller
是两个接口,分别与数据库和HTTP请求进行通信。Service
层是所有业务逻辑的归宿。总有一种情况是,服务中的一个方法使用多个仓库进行CRUD操作。因此,让服务方法注解为 @Transational
.
如果我说错了,请纠正我。在这里 Jdbi
的 Repository
成为 Dao
, Controller
成为 Resource
和 Service
遗体 Service
. 也许不同的人使用不同的层级架构,但我们姑且认为这是我的问题所在。
我希望达到同样的目的 交易处理 在Jdbi中和在Spring中一样,从意识形态上来说,因为它对我来说更有意义,不需要增加任何额外的层。
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()
}
}
有几点需要注意
我知道 onDemand
只能用于 abstract
类或接口,因此我不能实例化为 Service
使用 onDemand
. 我也不能让我的 Service
摘要。
很少有文章提出要做一个摘要 Repository
并使用 Transaction
在那里。但是按照我的想法,当我想到repository的时候,我看到它与repository有一对一的映射。entity/table
. 或者是相关实体。所以如果我想更新 movie
和 user
表中的同一个服务方法,把这两个事务语句放在某个方法下。XRepository
在我看来非常荒谬。它是业务逻辑的一部分,应该存在于 Service
.
我想我可以用 jdbi.inTransaction
和 jdbi.useTransaction
. 但在这种情况下,我必须附加每一个。Dao
手动。有没有更好的方法?
谅谅
你可以使用Jdbi的 @Transaction
来装饰你的bizlogic类中的方法。它将在事务中运行底层db查询。
假设 Repository
可由多个 Dao's
&假设这样的控制流程,这里是如何架构你的bizlogic(业务逻辑类)和仓库的一种方式。
Resource -> BizLogic -> Repository -> Dao
比如(Kotlin + Dropwizard + Jdbi)。
Resource
@GET
@Path("{Id}")
@Produces(MediaType.APPLICATION_JSON)
fun getAccount(
@PathParam("Id") Id: String,
@Suspended asyncResponse: AsyncResponse
) = asyncResponse.with {
accountManager.getAccount(Id)
}
方法在 BizLogic
@Transaction
suspend fun getAccount(Id: String): List<Account> =
accountRepository.getAccountsById(Id) ?: emptyList()
方法中 Repository
suspend fun getAccountsById(Id: String): List<Account>? = withContext(Dispatchers.IO){
accountDao.lookupById(Id)
}
Dao
@SqlQuery("select user_id, name, email from users where user_id = :id")
fun lookupById(@Bind("id") Id: String): List<Account>?
Ps: 你需要用以下方法处理repositorydao与jdbi实例的绑定 guice
或 spring-di