骆驼中的JPA组件无法自动重新连接到数据库

2022-01-19 00:00:00 spring java Hibernate jpa apache-camel

当我在应用程序运行时重新启动数据库时,JPA 组件 无法自动重新连接.

When I reboot my database while my application is running, JPA components cannot reconnect automatically.

2017-02-09 17:45:08,400 ERROR o.h.e.j.spi.SqlExceptionHelper(131) - Connection closed. - [Camel (camel-1) thread #99 - jpa://com.toto.Toto  ]

但仍然我可以在我的 CXF 路由中使用 spring-data 执行 SQL 请求.

But still I am able to execute SQL request with spring-data in my CXF routes.

我在 context.xml 中的数据源定义:

My datasource definition in context.xml :

<!-- JDBC connection -->
    <Resource name="jdbc/oracle"
            auth="Container"
            type="javax.sql.DataSource"
            username="toto"
            password="toto"
            factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
            driverClassName="oracle.jdbc.driver.OracleDriver"
            url="jdbc:oracle:thin:@toto:1568:SID"
            maxTotal="100"
            maxIdle="10"
            testOnBorrow="true"
            validationQuery="select 1 from dual"/>

这是我的 JPA 组件的样子:

And here is what my JPA component looks like :

    @Component
public class TotoPollerRoute extends RouteBuilder {

  private final String uri;

  private static final String POLLING_REQUEST = "select tt from Toto tt where tt.key = 1";

  public TotoPollerRoute() {
    super();
    final StringBuilder uriBuilder = new StringBuilder();
    uriBuilder.append("jpa://");
    uriBuilder.append(TotoPollerRoute.class.getName());
    uriBuilder.append("?");
    uriBuilder.append("consumeDelete=false");
    uriBuilder.append("&consumeLockEntity=true");
    uriBuilder.append("&consumer.SkipLockedEntity=true");
    uriBuilder.append("&maximumResults=10");
    uriBuilder.append("&consumer.query=");
    uriBuilder.append(POLLING_REQUEST);
    this.uri = uriBuilder.toString();
  }

  @Override
  public void configure() {
    // @formatter:off
    from(uri)
        .to("TotoMainRoute");
    // @formatter:on
  }
}

有什么想法吗?

推荐答案

经过深入调试,我终于发现我的 JPA 组件没有使用 Spring 上下文中声明的 EntityManagerFactory.

After some deep debugging I finally figured out my JPA components weren't using the EntityManagerFactory declared in the Spring context.

两种解决方法:

  1. 修改每个 JPA 组件上的 JPA uri 并添加 sharedEntityManager 选项:

  1. Modify the JPA uri on each JPA component and add the sharedEntityManager option :

private final String uri = "jpa://TotoPollerRoute?consumeDelete=false"
    + "&consumeLockEntity=true"
    + "&consumer.SkipLockedEntity=true"
    + "&maximumResults=10"
    + "&sharedEntityManager=true"
    + "&joinTransaction=false"
    + "&consumer.query=select tt from Toto tt where tt.key = 1";

  • 在 Spring 中实例化 JPA 组件:

  • Instanciate JPA component in Spring :

    @Bean
    public JpaComponent jpa() {
        final JpaComponent jpa = new JpaComponent();
        jpa.setSharedEntityManager(true);
        jpa.setJoinTransaction(false);
        return jpa;
    }
    

  • 相关文章