Решение вашего вопроса полностью зависит от требований отдельных лиц, если кто-то желает ограничить сеансы, предоставляемые 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;
}
}
Надеюсь, что вышесказанное устранит ваши сомнения по поводу вашего запроса.