Connection to DB using Hibernate

To connect to DB using Hibernate users have to make the next steps:

  • Create an environment at CirrusGrid
  • Add a database node to this environment
  • Modify some configuration files in a web-app
  • Execute queries

Let’s do it step by step:

1. Create environment with a database server (MySQL in our case):

jelastic db hibernate env created

2. Create a new user in a database:
How to create a new user – click here.

Database name : cirrusgridDb  
Username : cirrusgrid  
Password : cirrusgrid

For this example we’ve created table books with fields book_name and book_author inside the cirrusgridDb database.

3. Modify the following configuration files of your web-application: hibernate.cfg.xml

    <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}</property>
    <property name="hibernate.connection.username">cirrusgrid</property>
    <property name="hibernate.connection.password">cirrusgrid</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="com/Testdata.hbm.xml"/>

Tip: Don’t miss to put the correct values to the hibernate.connection.url string instead of the text inside curly brackets.
where {node_id} - ID of the container with MySQL server you want to receive the access to. It can be seen at the dashboard:

jelastic db hibernate node id


  <schema-selection match-catalog="cirrusgridDb"/>
  <table-filter match-name="books"/>

For the next step we’ve used reverse engineering mechanism and got 2 files in our web-project:

  • Books.hbm.xml Also you need to create the file but do not need to change it.

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

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

Note that you have to put the connector for database (.jar library) to your project or to the appropriate web-server’s folder in the environment.

Powered by BetterDocs