使用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());
}
}
}
答案 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;
}