使用jpa在Hibernate中不会关闭连接。更多连接在Sql server manager中打开

时间:2017-07-21 05:43:56

标签: hibernate jpa

使用hibernate和Jpa进行数据库连接。我在日志中有时会遇到连接错误。当我在Sql服务器中看到仍然连接是活着的。

以下是我的代码:

public class DBConnectionUtil {

  private static final Logger LOGGER = Logger.getLogger(DBConnectionUtil.class);
  private static final EntityManagerFactory emFactory;

  static {

    emFactory = Persistence.createEntityManagerFactory("iswift_db");
  }
  private EntityManager entityManager;

  public EntityManager getEntityManager() {
    Map<String, String> props = new HashMap<String, String>();
    props.put("openjpa.ConnectionRetainMode", "always");
    props.put("openjpa.FlushBeforeQueries", "with-connection");
    entityManager = emFactory.createEntityManager(props);
    entityManager.setFlushMode(FlushModeType.COMMIT);
    return entityManager;
  }

  public void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
  }

  public void closeEntityManager() {
    try {
      if (entityManager != null) {
        entityManager.close();
      }
    } catch (Exception e) {
      LOGGER.error("Error occured in closing entitymanager" + e.getMessage());
    }
  }

}

1 个答案:

答案 0 :(得分:0)

试试这个:

 public EntityManager getEntityManager() {
    if ( entityManager == null ) {
      Map<String, String> props = new HashMap<String, String>();
      props.put("openjpa.ConnectionRetainMode", "always");
      props.put("openjpa.FlushBeforeQueries", "with-connection");
      entityManager = emFactory.createEntityManager(props);
      entityManager.setFlushMode(FlushModeType.COMMIT);
    }
    return entityManager;

  }