I am currently trying to learn about the hibernate sessions. So, I am trying to process run some processes using CompletableFuture in java. The function inside the supplyAsync()
has some DB processes to run. Earlier, I was running into no session currently bound to execution context
even when I added @UnitOfWork
to my resource.
In order to solve the issue, now I am currently opening and closing the session within the DAO's method findAll()
. Since, the codebase is very big, I am going to only add a file which can illustrate the concern.
Main.java
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class Supply {
public static void main(String... args) throws ExecutionException, InterruptedException {
final CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> doSomethingAndReturnA())
.thenApply(a -> convertToB(a));
System.out.println(future.get());
}
private static int convertToB(final String a) {
System.out.println("convertToB: " + Thread.currentThread().getName());
return Integer.parseInt(a);
}
private static String doSomethingAndReturnA() {
System.out.println("doSomethingAndReturnA: " + Thread.currentThread().getName());
try {
// some DB processes
List<String> list = someDAO.findAll(); // opening and closing session in findAll()
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
public List<String> findAll() throws Exception{
List<String> temp = null;
Session session = sessionFactory.openSession();
LOGGER.debug("Opened the session");
try {
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
try {
temp = list((Query<String>) namedQuery("something.findAll"));
transaction.commit();
}
catch (Exception e) {
transaction.rollback();
throw new Exception(e.getMessage());
}
} finally {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
return temp;
}
Since, I added
@UnitOfWork
in my resource file where I am calling mydoSomethingAndReturnA()
directly, do I need to worry about separate sessions which are going to be opened infindAll()
.I also read that I can access
getCurrentSession()
which will only create a session if it doesn't exists but for that I need ahibernate.cfg.xml
and addcurrent_session_context_class
. Is there a way to write that file?
Of the two methods getCurrentSession()
vs opening and closing sessions, which is more efficient and scalable.