我正在用Java创建一个web应用程序,并希望使用贾瓦林框架。
议题/问题:
EntityManager对象对Javalin请求处理程序可用的最佳方法是什么?更新:更多的上下文
我想在我的javalin应用程序中使用JPA (通过Hibernate)。JPA的核心概念是使用EntityManager实例访问数据库。要创建一个EntityManager,有一个EntityManagerFactory。
我目前所做的是创建一个全局EntityManagerFactory和使用数据库调用factory.createEntityManager()的处理程序。
虽然这是可行的,但我想知道是否有其他建议的分摊?来自Flask/SQLAlchemy/Python背景的ORM会话(EntityManager等效)通常可以作为请求绑定对象使用。
发布于 2022-10-05 22:51:23
最后,我实现了以下内容:
EntityManagerFactory。在启动时创建一个Javalin实例。然后打电话给enableRequestBoundEntityManager(javalinApp, entityManagerFactory)。EntityManager时,请使用Context.entityManager扩展属性。即:
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")!!
}https://stackoverflow.com/questions/71323135
复制相似问题