连接不会在 Hibernate 中使用 jpa 关闭.更多连接在 Sql 服务器管理器中打开



使用休眠和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());
}
}
}

试试这个:

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;
}

最新更新