我通过hibernate连接一个MYSQL数据库,我似乎有一些进程在会话结束后没有被杀死。我已经在每个会话上调用了flush和close但是当我检查服务器时,最后一个进程仍然在那里使用sleep命令。这是我遇到的一个新问题,昨天并非如此。当我完成一个会话时,有什么方法可以确保杀死这些进程。 下面是我的一个班级的例子。
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;
}
答案 0 :(得分:1)
您最后应调用sessionFactory.close()
,这将释放连接池中的所有连接。
请注意,通常您应该为整个应用程序创建一个会话工厂,然后可以根据需要创建任意数量的会话。创建会话工厂非常昂贵。