hibernate - 我们可以限制从 SessionFactory 获得的会话数吗?
问题描述
我们可以限制从 SessionFactory 获得的会话吗?它是否与数据库可以处理的连接数内部链接?
如果是,SessionFactory 的哪个属性用于设置限制值?
如果我的数据库可以处理的连接数少于创建的会话数会怎样?
先感谢您。
解决方案
您的问题的解决方案完全取决于个人的要求,如果希望限制由 授予的会话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;
}
}
我希望以上内容可以消除您对查询的疑问。
推荐阅读
- elasticsearch - 弹性搜索性能
- ruby - 如何在 Windows 机器上使用 RSpec 和 Watir 运行并行测试?
- javascript - 使用Angular如何在表格行内停止复选框单击事件的传播()?
- java - 从两个自定义对象列表中删除公共元素
- python-3.x - 将 HTTP 头字典字符串加载到 JSON 中并解析它
- c# - 初始化列表属性
- css - 如何在更改突出显示日期的背景后刷新 mat-calendar
- r - 如何部分重新排序堆叠条形图中每个条形的堆栈?
- python - 如何在 PyQt4 的动态复选框列表中检查 stateChanged
- python - ModuleNotFoundError:没有名为“unidecode”的模块,但我已安装该模块