我们可以限制SessionFactory可以获得的会话数吗?

时间:2018-05-26 07:53:56

标签: hibernate session sessionfactory

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

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

如果我的数据库可以处理的连接数少于创建的会话数,会发生什么?

提前谢谢。

1 个答案:

答案 0 :(得分:2)

您的问题的解决方案完全取决于个人的要求,如果希望限制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;
}

}

我希望上述内容能够清除您对查询的疑问。