Connection to DB using Hibernate
To connect to a database using Hibernate, follow these steps:
- Create an environment on the platform.
- Add a database node to this environment.
- Edit the configuration files within your web application.
- Execute queries.
Let’s go through each step in detail:
Step 1. Create an environment with a database server (e.g., MySQL):
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.
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>
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.
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.