Tuesday, April 5, 2016

Hibernate Tables and Transactions

Transactions:

         In the last post, we have seen up to Session Factory and Session. Now it’s the time to implement Transaction code here. In hibernate.cfg.xml, we have configured transaction is our own. So we need to implement the transaction code. See the below,

try { 
     Transaction transaction = session.getTransaction(); 
     transaction.begin();
     
     //Your code here

     transaction.commit(); 
    } catch (Exception e) { 
       if (session.getTransaction().isActive()) { 
             session.getTransaction().rollback(); 
       } 
      throw e;
}

         First we need to create a transaction reference for transaction with the help of getTransaction() method. After that we should invoke begin() method immediately to begin the transaction. If there is no any code error(Business logic) in your code , then it will be commit by transaction. Suppose if any exception occurred, catch block have the concept for rollback. 

Tables:


       Still now, We have learned about session sessionFactory and Transaction. Next , we can see mapping configuration. 

public class Employee { 
private Long id; 
private String firstName; 
private String lastName; 
//Setters and Getters

The class have two attributes and below is the configured mapping xml for Employee class.

hibernate-mapping package :


   
   
      
   

         
         
   


          Mapping xml will start with XML element hibernate-mapping tag and it have the option to put your package configuration.

<class name="Employee" table="T_Employee"> :

          Class name representing name of the class and table mentioning table name for the class.

<id name="id" column="ID">

         Id name mentioning name of the ID and column mentioning name of the column of T_Employee table.

<generator class="native"/>:

          Specifies the generation strategy and the class native means, based on your database support,  sequence id will be generated. You can set lot of other option based on your need like increment, identity etc.,

Finally remaining two’s are property name of your Employee class.


private void persistEmployee(Session session) throws Exception {
 try { 
     Transaction transaction = session.getTransaction();  
     transaction.begin(); Employee emp = new Employee(); 
     emp.setFirstName("First Name"); 
     emp .setLastName("Last Name”);
     session.save(emp);
 transaction.commit(); 
} catch (Exception e) {
 if (session.getTransaction().isActive()) {
 session.getTransaction().rollback(); 
 } 
   throw e; 
 } 
}

After executing this code, you could see below output in console tab. 


Hibernate:
 drop table T_Employee if exists
 Hibernate:
 create table T_Employee ( 
ID bigint generated by default as identity, FIRST_NAME varchar(255), LAST_NAME varchar(255), primary key (ID) ) 
Hibernate: 
insert into T_Employee (ID, firstName, lastName, ID_ID_CARD) values (null, ?, ?, ?)


You are seeing query in console window due to hibernate cfg xml configuration show_sql as true.  And another thing here is, hibernate using prepared statement so we could not see values in console.

If you are interested to see values in console as usual you need to add logging. Configure logging.properties in main resources location. (src/main/resources). You should set the logging level org.hibernate.type to FINEST.

logging.properties
  
.handlers = java.util.logging.ConsoleHandler
.level = INFO

java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

org.hibernate.SQL.level = FINEST
org.hibernate.type.level = FINEST

After did this logging settings, you could see below output in console.

DEBUG:
insert into T_Employee (ID, FIRST_NAME, LAST_NAME, ID_ID_CARD) values (null, ?, ?, ?)

TRACE: binding parameter [1] as [VARCHAR] - [FirstName] TRACE: binding parameter [2] as

                                             [VARCHAR] - [LastName]
TRACE: binding parameter [3] as [BIGINT] - [null]


No comments:

Post a Comment