Setting Up Hibernate and Servlet with Eclipse

Mr. Brave
3 min readJun 9, 2024

--

For those who are stepping into the world of Java programming for the first time, they either start with Android or Spring.

If you want to start with Spring, why not begin with Servlet?

Creating Your First Project

The powerful and free Eclipse IDE has been a boon for Java developers, not only providing many packages but also continuous version updates. Let’s see how to use it. (Depending on the version, the interface may be slightly different)

  1. Open Eclipse and go to File > New > Project….
  2. Select Web > Dynamic Web Project and click Next.
  3. Name the project servlet_hibernate_example.
  4. Set the target runtime to Apache Tomcat.
  5. Click Finish.
Create a project with Eclipse

Now you can run the service by right-clicking on the ‘servlet_hibernate_example’ project on the left side and selecting ‘Run’. Next, let’s see how to connect to the database to complete the basic functionality.

Using Hibernate and JPA, you can persist Java objects to the database. This means that you can use Java classes to represent records in database tables and manipulate the database by performing operations on these objects. This allows developers to handle database operations using familiar object-oriented concepts while providing better readability and maintainability.

According to my approach:

  1. You need to import the relevant libraries first (you can add the corresponding version from the Maven Repository website)
  2. And create a resources folder in the directory, and then create a hibernate.cfg.xml (used to configure the database connection object)

The following uses MySQL as the database :

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/example</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password"><your password></property>

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

</session-factory>

</hibernate-configuration>

3. Next, let’s verify whether the database connection configuration is successful through a small program.

Similarly, add a utils folder to the project and add a HibernateUtils.java file. Then, add the following code.

public class HibernateUtil {
private static final Logger logger = LogManager.getLogger(HibernateUtil.class);
private static final SessionFactory sessionFactory = buildSessionFactory();

public static SessionFactory buildSessionFactory() {
if (sessionFactory == null) {
try {
// Loading higernate.cfg.xml's configuration
Configuration configuration = new Configuration();
configuration.configure(
new File("<your project path>\resources\\hibernate.cfg.xml"));

return configuration.buildSessionFactory();
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
}
}
return sessionFactory;
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}

We use the MVC architecture to design the entire processing process. Here’s a brief explanation :

Model

In the MVC architectural pattern, the Model is responsible for “implementing business logic and handling data.”

Controller

In the MVC architectural pattern, the Controller is responsible for “forwarding Http requests.”

View

In the MVC architectural pattern, the View is responsible for “using Html templates to present data.”

MVC Design Pattern

After understanding the MVC architecture, we test the connection in the Model layer by adding the following code :

public class ExampleDaoImpl implements ExampleDao {
private SessionFactory sessionFactory;

private static final Logger logger = LogManager.getLogger(ExampleDaoImpl.class);

public ExampleDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

@Override
public List<Model> getAll() {
try (Session session = sessionFactory.getCurrentSession()) {
return gsession.createQuery("from Model").list();
} catch (Exception e) {
logger.error(ExceptionUtils.getStackTrace(e));
throw new ExceptionInInitializerError(e);
}
}

}

If the returned result is successful, it means that the configuration for connecting to the database is correct. (The best way is to use unit testing for verification)

Finally, you can modify the default code in the Servlet to complete the required functionality.

@WebServlet("/example")
public class BaseServlet<T> extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}

The above is how to build a basic backend service using Servlet and Hibernate.

If there are any errors or suggestions, please leave a comment and reply. Thank you for your patient reading.

--

--

Mr. Brave

Software Engineer. My favorite food is sausages and mash.