首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Javalin应用程序中使用JPA

在Javalin应用程序中使用JPA
EN

Stack Overflow用户
提问于 2022-03-02 13:00:02
回答 1查看 301关注 0票数 1

我正在用Java创建一个web应用程序,并希望使用贾瓦林框架。

议题/问题:

  • JPA (通过hibernate) web应用程序中使用贾瓦林的最佳方法是什么?
  • 也就是说,使JPA EntityManager对象对Javalin请求处理程序可用的最佳方法是什么?

更新:更多的上下文

我想在我的javalin应用程序中使用JPA (通过Hibernate)。JPA的核心概念是使用EntityManager实例访问数据库。要创建一个EntityManager,有一个EntityManagerFactory

我目前所做的是创建一个全局EntityManagerFactory和使用数据库调用factory.createEntityManager()的处理程序。

虽然这是可行的,但我想知道是否有其他建议的分摊?来自Flask/SQLAlchemy/Python背景的ORM会话(EntityManager等效)通常可以作为请求绑定对象使用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-05 22:51:23

最后,我实现了以下内容:

  • 在启动时创建一个EntityManagerFactory。在启动时创建一个Javalin实例。然后打电话给enableRequestBoundEntityManager(javalinApp, entityManagerFactory)
  • 每当处理程序需要EntityManager时,请使用Context.entityManager扩展属性。

即:

代码语言:javascript
复制
fun main() {
    val app = Javalin.create()
    val emf = createEntityManagerFactorySomehow()

    enableRequestBoundEntityManager(app, emf)

    app.get("/list/") { ctx -> ctx.json(
        ctx.entityManager.createQuery("select ... from ...").resultList
    ) }

    app.start()
}

/**
 * Adds an `entityManagerFactory` application attribute, and sets up clean up after requests have been handled
 */
fun enableRequestBoundEntityManager(app: Javalin, entityManagerFactory: EntityManagerFactory) {
    app.attribute("entityManagerFactory", entityManagerFactory)

    app.after {
        val entityManager: EntityManager? = it.attribute("entityManager")
        if (entityManager != null) {
            entityManager.close()
        }
    }
}

/**
 * Returns a JPA entity manager scoped to the Javalin context
 */
val Context.entityManager: EntityManager
    get() {
        if (this.attribute<EntityManager>("entityManager") == null) {
            this.attribute("entityManager", this.appAttribute<EntityManagerFactory>("entityManagerFactory").createEntityManager())
        }
        return this.attribute("entityManager")!!
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71323135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档