Unable to access new File("webapp/WEB-INF/classes/hibernate.cfg.xml") in a servlet environment

26 Views Asked by At

I am creating a hibernate project and I have problems creating a sessionFactory in a servlet. I'm using Glassfish 7.0.82 and JDK 20.

I have a HibernateUtil class

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.io.File;

public class HibernateUtil{
private static  SessionFactory sessionFactory;

private static SessionFactory buildSessionFactory() {
    File configFile = new File("webapp/WEB-INF/classes/hibernate.cfg.xml");
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .configure(configFile)
            .build();
    try {
        sessionFactory = new MetadataSources(registry)
                .addAnnotatedClass(SiteUser.class)
                .buildMetadata()
                .buildSessionFactory();
        return sessionFactory;
    } catch (Exception e) {
        System.err.println("Initialisation de la SessionFactory a échoué : " + e);
        StandardServiceRegistryBuilder.destroy(registry);

        throw new ExceptionInInitializerError(e);
    }
}

public static SessionFactory getSessionFactory() {
    if(sessionFactory == null){
        sessionFactory = buildSessionFactory();
    }
    return sessionFactory;
}

public static void shutdown() {
    if (sessionFactory != null) {
        sessionFactory.close();
    }
}
}

that I basically use to create my sessionFactory and keep it unique thanks to the singleton pattern. I also have a method used to add a user to my MySQL database (I've tested this logic with junit and it's adding users in my database).

public void addUser(SiteUser user) {
    try(Session session = HibernateUtil.getSessionFactory().openSession()){
        //security
        session.beginTransaction();
        session.persist(user);
        session.getTransaction().commit();
    }catch(Exception e){
        e.printStackTrace();
    }
}

And finally, I receive some form informations in a servlet I made to add users into my database :

import java.io.*;
import java.time.LocalDate;

import com.example.projetjee.DAO.UserDAOImpl;
import com.example.projetjee.Hibernate.HibernateUtil;
import com.example.projetjee.Hibernate.SiteUser;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.hibernate.Session;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    String name = request.getParameter("name");
    String surname = request.getParameter("surname");
    String username = request.getParameter("username");
    String email = request.getParameter("email");
    LocalDate birthDate = LocalDate.parse(request.getParameter("birthDate"));
    String gender = request.getParameterValues("gender")[0];
    String password = request.getParameter("password");

    boolean basicUser = false;

    SiteUser newUser = new SiteUser(name,surname,username,email,birthDate,gender,password,basicUser,basicUser);

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    System.out.println(newUser.toString());
    UserDAOImpl userDao = new UserDAOImpl();
    userDao.addUser(newUser);
    session.getTransaction().commit();
    }

The problem is, when I try to use this piece of code, I receive an error because the servlet is handled by glassfish that is not actually deployed at the same place as my project, so it does not have access to src/main/webapp/WEB-INF/classes/hibernate.cfg.xml but rather Glassfish/src/... that doesn't exist.

You'll notice I opened a transaction before my addUser() method that already opens a transaction and it was only for test purposes because the addUser method was not doing anything and the error started appearing here. So I guess it is why it wasn't doing anything.

My question would be : how could I make it so that my HibernateUtil class could access the hibernate.cfg.xml file even if I am in a servlet deployment context. Thanks by advance.

0

There are 0 best solutions below