Object-relational Mapping Using JPA, Hibernate and Spring Data JPA. Native Hibernate configuration

Object-relational Mapping Using JPA, Hibernate and Spring Data JPA. Native Hibernate configuration

NATIVE HIBERNATE CONFIGURATION

The org.hibernate.SessionFactory Hibernate interface is the native correspondent of the JPA EntityManagerFactory.

To configure the native Hibernate, we may use a hibernate.properties Java properties file, or a hibernate.cfg.xml XML file. We chose the second option, and the configuration contains database and session-related options. This XML file is generally placed under the folder src/main/resource or src/test/resource. As we need the information for the Hibernate configuration in the tests, we chose the second location alternative.

Listing 5 The hibernate.cfg.xml configuration file


<hibernate-configuration>                        #1
<session-factory>                              #2
    <property

    name="hibernate.connection.driver_class">                
            com.mysql.cj.jdbc.Driver             #3
    </property>                                                        
    <property name="hibernate.connection.url">                         
          jdbc:mysql://localhost:3306/CSCS       #4
    </property>
    <property name="hibernate.connection.username">

    root</property>                           #5
    <property name="hibernate.connection.password">

   </property>                               #6
    <property

    name="hibernate.connection.pool_size">

    50</property>                             #7
    <property name="hibernate.hbm2ddl.auto">

    create</property>                         #8
</session-factory>
</hibernate-configuration>

  • First, we use the tags to indicate the fact that we are configuring Hibernate #1, more exactly the SessionFactory object #2. SessionFactory is an interface and we need one SessionFactory to interact with one database.
  • We indicate the JDBC properties - driver #3, URL of the database #4, username #5, and password #6 to access it.
  • We limit the number of connections waiting in the Hibernate database connection pool to 50 #7.
  • Every time the program is executed, the database will be created from scratch #8. This is ideal for automated testing when we want to work with a clean database for every test run.

Object-relational Mapping Using JPA Hibernate and Spring Data JPA Native Hibernate configuration.jpg


Let’s save an Item to the database using native Hibernate.

Listing 6 The ItemHibernateTest class

public class ItemHibernateTest {

   private static SessionFactory    

     createSessionFactory() {
        Configuration configuration = new    

            Configuration();                     #1
     configuration.configure().

        addAnnotatedClass(Item.class);           #2
     ServiceRegistry serviceRegistry = new   

       StandardServiceRegistryBuilder(). #3
     applySettings(configuration.

getProperties()).build(); #3
     return configuration.

     buildSessionFactory(serviceRegistry);    #4
}

@Test
void saveRetrieveItem() {
   try (SessionFactory sessionFactory =

       createSessionFactory();                #5

     Session session =

       sessionFactory.openSession()){         #6

     session.beginTransaction();              #7
        Item item = new Item();                  #8
        item.setInfo(

            "Item from Hibernate");         #8
        session.persist(item);                   #9
        session.getTransaction().commit();      #10
   }
}

  • To create a SessionFactory, we need to create a Configuration #1, to call the configure method on it, and to add Item to it as annotated class #2. The execution of the configure method will load the content of the default hibernate.cfg.xml file
  • We create and configure the service registry #3. A ServiceRegistry hosts and manages services that need access to the SessionFactory
  • We build a SessionFactory using the configuration and the service registry we have previously created #4
  • The SessionFactory created with the createSessionFactory method we have previously defined is passed as an argument to a try with resources, as SessionFactory implements the AutoCloseable interface #5. Similarly, we begin a new session with the database by creating a Session #6, which also implements the AutoCloseable interface. This is our context for all persistence operations
  • Get access to the standard transaction API and begin a transaction on this thread of execution #7
  • Create a new instance of Item class, and set its info property #8
  • The transient instance becomes persistent on the side of the persistence context #9
  • Synchronize the session with the database and close the current session on commit of the transaction automatically #10
  • As in the case of JPA, there is no SQL code and no JDBC usage. There are no CRUD (create, read, update, delete) operations inside the Java code, but only working object-oriented way, with classes, objects, and methods. The translation to each SQL dialect is made by the ORM which also addresses portability 

 

Interested in learning how to program with Java or in upgrading your Java programming skills?

Check out our trainings
Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin , Java Champion; Java Chapter Lead; Author at Pluralsight and Manning

Tudose, Florin-Catalin Tudose author linkedin

Java Champion; Java Chapter Lead; Author at Pluralsight and Manning