2010-03-28 106 views
0

我通过hibernate连接MYSQL数据库,并且我似乎有进程在完成会话后没有被杀死。我在每个会话中调用了flush和close,但是当我检查服务器时,最后一个进程仍然存在,并带有睡眠命令。这是我遇到的一个新问题,昨天并非如此。有没有什么办法可以确保当我完成一个会议时,这些流程的杀伤力。 下面是我的一个类的例子。杀死进入睡眠状态的Mysql进程命令

public JSONObject check() 
{ 
    //creates a new session needed to add elements to a database 
    Session session = null; 

    //holds the result of the check in the database 
    JSONObject check = new JSONObject(); 
    try{ 
     //creates a new session needed to add elements to a database 
     SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
     session = sessionFactory.openSession(); 


     if (justusername){ 

      //query created to select a username from user table 
      String hquery = "Select username from User user Where username = ? "; 

      //query created 
      Query query = session.createQuery(hquery); 

      //sets the username of the query the values JSONObject contents 
      query.setString(0, username); 

      // executes query and adds username string variable 
      String user = (String) query.uniqueResult(); 

      //checks to see if result is found (null if not found) 
      if (user == null) 
      { 
       //adds false to Jobject if not found 
       check.put("indatabase", "false"); 
      } 
      else 
      { 
       check.put("indatabase", "true"); 
      } 

      //adds check to Jobject to say just to check username 
      check.put("justusername", true); 

     } 
     else 
     { 
      //query created to select a username and password from user table 
      String hquery = "Select username from User user Where username = :user and password = :pass "; 
      Query query = session.createQuery(hquery); 

      query.setString("user", username); 
      query.setString("pass", password); 

      String user = (String) query.uniqueResult(); 

      if(user ==null) 
      { 
       check.put("indatabase", false); 
      } 
      else 
      { 
       check.put("indatabase", true); 
      } 

      check.put("justusername", false); 

     } 


     }catch(Exception e){ 

     System.out.println(e.getMessage()); 
      //logg.log(Level.WARNING, " Exception", e.getMessage()); 

    }finally{ 
    // Actual contact insertion will happen at this step 

     session.flush(); 
     session.close(); 

    } 
    //returns Jobject 
    return check; 
} 

回答

1

您应该在末尾调用sessionFactory.close(),这将释放连接池中的所有连接。

请注意,通常您应该为整个应用程序设置一个会话工厂,然后可以根据需要创建多个会话。创建会话工厂的代价非常高。