首页 > 解决方案 > 我们可以限制从 SessionFactory 获得的会话数吗?

问题描述

我们可以限制从 SessionFactory 获得的会话吗?它是否与数据库可以处理的连接数内部链接?

如果是,SessionFactory 的哪个属性用于设置限制值?

如果我的数据库可以处理的连接数少于创建的会话数会怎样?

先感谢您。

标签: hibernatesessionsessionfactory

解决方案


您的问题的解决方案完全取决于个人的要求,如果希望限制由 授予的会话Session-Factory可以通过创建自己的实用程序类来完美实现,您可以在其中定义自己的业务逻辑来Sessions授予SessionFactory. 我有下面的代码,它以非常一般的形式显示了实现结果的方法。

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class FactoryUtil  {

public static SessionFactory factory=null;  //Here I have Initialized the object of SessionFactory to null.
public static final int MAX_SESS = 10;  //Here user can declare value of MAX_SESS to the number of session objects to be granted by the SessionFactory.
public static int counter = 0;  //Similarly, user can take counter to execute the logic till the limit is specified above.

 /*declaring below method as private static so that it 
   should only be accessible through the name of the class and not by any 
   other object outside the class also it will have common logic to all 
   the objects of the class. It will return the object of type 
   SessionFactory which will now hold the config required for 
   communication from your java application related to specific database. 
 */

private static SessionFactory getFactory() {

    System.out.println("Receiving new call to create new SF object.");

    if(factory==null){

       System.out.println("New SeSFaC created.");

        factory = new Configuration().configure("hibernate.mysqlcfg.xml").buildSessionFactory();

    }

    return factory;
}

/*Specify the logic as per your requirement. Here I'm jst validating 
  the number of session objects to be created by SessionFactory are equal 
  to the MAX_SESS the user wants to be generated. Similarly I have tried 
  catch the exception if the number of sessions granted exceeds the limit 
  specified and display the warning msg back to the user. It will return 
  me the session object which is created using the config provided inside 
  the getFactory method.  
*/   

public static Session getSession() throws Exception{

Session ss = null ;

        if(counter <= MAX_SESS){

            ss = FactoryUtil.getFactory().openSession();

            counter++;
        }
        else {

            System.out.println("No.of Session limit exceeded.");
            try{
                throw new Exception("No. of limit exceed"); 
            }
            catch(Exception e){
             e.printStackTrace();
            }
        }


    return ss;
}

}

我希望以上内容可以消除您对查询的疑问。


推荐阅读