Connection to DB using Hibernate

To connect to a database using Hibernate, follow these steps:

  1. Create an environment on the platform.
  2. Add a database node to this environment.
  3. Edit the configuration files within your web application.
  4. Execute queries.

Let’s go through each step in detail:

Step 1. Create an environment with a database server (e.g., MySQL):

Create Database Server

Step 2. Create a new user in the database:

Refer to the documentation on how to create a new user.

For this example, use the following credentials:

  • Database name: accuwebcloudDb
  • Username: accuwebc
  • Password: accuwebc

Create a table named books with fields book_name and book_author inside the accuwebcloudDb database.

Save $100 in the next
5:00 minutes?

Register Here

Step 3. Modify the following configuration files of your web application:

hibernate.cfg.xml


<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://mysql{node_id}.{your_env_name}.{hoster_domain}:3306/accuwebcloudDb</property>
    <property name="hibernate.connection.username">accuwebc</property>
    <property name="hibernate.connection.password">accuwebc</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="com/Testdata.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
Note: Replace the text inside curly brackets with the correct values in the hibernate.connection.url string.

Example connection URL:

jdbc:mysql://mysql{node_id}.{your_env_name}.{hoster_domain}:3306/accuwebcloudDb

Where:

  • {node_id}: ID of the container with the MySQL server you want to access. You can find it on the dashboard.

Node ID

hibernate.revenge.xml


<hibernate-reverse-engineering>
  <schema-selection match-catalog="accuwebcloudDb"/>
  <table-filter match-name="books"/>
</hibernate-reverse-engineering>

For the next step, we employed a reverse engineering mechanism to generate two files within our web project:

  • Books.java
  • Books.hbm.xml

Additionally, you’ll need to create the HibernateUtil.java file, but no changes are necessary within it.

Step 4. Create a simple Java method to add a new row to the books table in our database:


public void addBook(){
        Session s = HibernateUtil.getSessionFactory().getCurrentSession();        
        s.beginTransaction();       
            Books book = new Books("romeo and juliet","william shakespeare ");
            s.save(book);    
        s.getTransaction().commit();    
}

Ensure that you have added the database connector (.jar library) to your project or to the appropriate web server’s folder in the environment.

Save $100 in the next
5:00 minutes?

Register Here