【问题标题】:Inject java.sql.Connection into controller for Ninja Framework将 java.sql.Connection 注入 Ninja Framework 的控制器
【发布时间】:2016-04-02 01:13:18
【问题描述】:

我想使用 JOOQ 从 Ninja Framework 访问我的数据库。如何从控制器获取 JDBC 连接?

以下是我发现不太奏效的资源。

How to retrieve the datasource used by a persistence unit programmatically - 从 EntityManager 获取连接的繁琐步骤。

http://blog.jooq.org/2015/05/26/type-safe-queries-for-jpas-native-query-api/ - 通过在 JOOQ 中构建查询并传递给 EntityManager.createNativeQuery 来工作。它是功能性的,但不如仅仅拥有连接那么好。

我可以像这样将连接注入控制器吗:

public Result myController(@DBConnection Connection connection) {
    List<String> articles = DSL.using(connection).selectFrom(ARTICLE).fetch(ARTICLE.TITLE);
    return Results.html().render("template", articles);
}

DropWizards 有一个看起来像赢家的插件:https://github.com/benjamin-bader/droptools/tree/master/dropwizard-jooq

public BlogPost getPost(@QueryParam("id") int postId, @Context DSLContext database) {
    BlogPostRecord post = database
        .selectFrom(POST)
        .where(POST.ID.equal(postId))
        .fetchOne();

    // do stuff
}

【问题讨论】:

  • 有什么方法可以在 ninja 框架中获取DataSource 吗?
  • 我不能说。似乎 EntityManager 是唯一容易获得的。

标签: java jdbc dependency-injection ninjaframework


【解决方案1】:

跟进@LukasEder 的回答,这就是方法:

    HibernateEntityManagerFactory hibernateEntityManagerFactory = ((EntityManagerImpl) entityManager).getFactory();
    SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) hibernateEntityManagerFactory.getSessionFactory();
    C3P0ConnectionProvider c3P0ConnectionProvider = (C3P0ConnectionProvider) sessionFactoryImpl.getConnectionProvider();

    Connection connection = c3P0ConnectionProvider.getConnection();

这显然是非常非常非常奇怪和糟糕的代码。

一个干净的解决方案是通过 Ninja 直接提供对 Connection / DataSource 的访问(将连接池与 Hibernate 或任何实现分开)。这并不难,部分是在 ebeans 插件中完成的。如果您有兴趣贡献代码,请在我们的邮件列表中讨论这个问题:)

【讨论】:

【解决方案2】:

没有任何选项可以直接从 ninja 框架中检索 JDBC ConnectionDataSource,标准方法应该是从 EntityManager 中“解包”它:

Connection connection = em.unwrap(Connection.class);

另请参阅:How to get DataSource or Connection from JPA2 EntityManager in Java EE 6

此处记录了一种特定于 Hibernate 的方法:How to retrieve the datasource used by a persistence unit programmatically

【讨论】:

  • 我用这个得到了一个 NPE,但我不知道为什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-21
  • 2018-12-18
  • 2016-11-16
  • 2016-01-26
  • 1970-01-01
  • 2016-04-09
相关资源
最近更新 更多