1.

Explain cascading and the different types of cascading with reference to Hibernate Annotations?

Answer»

An exception is an error which is generated at run-time and INTERRUPTS the program flow. An exception can be generated due to a number of reasons. One of the reasons could be entering of invalid DATA, or a necessary file is not found or the exception could be due to network issues etc. 

 The EXCEPTIONS are handled by the Entity Manager which calls the close() method. This method discards any changes made and rolls back the database transaction. The Entity Manager handles core exceptions like:  

  • IllegalArgumentException: Wrong argument, or failing to recognize argument, or having the incorrect format, or incorrect number of arguments etc. 
  • EntityNotFoundException: An Entity was expected but did not match the requirement, or an Entity was expected but was not passed 
  • TransactionRequiredException: A Transaction is expected but is not found. This exception occurs due to missing Transaction object 
  • IllegalStateException: Wrong way of using the Entity Manager 

When HIBERNATE interacts with the database it throws SQLException. Hibernate provides better exception handlers than the JDBCException. Developers can use the try and catch block to handle the exceptions. The line of code that may cause an exception is enclosed in a try block and according to the exception thrown, the exception handler is added in the catch block. In the below example, the code for data UPDATING is enclosed in the try block which will be handled by Hibernate Exception in catch block. 

Example.java 

importcom.hibernate.exception.handling.model.Student;  importcom.hibernate.exception.handling.util.HibernateUtil;  importorg.hibernate.HibernateException;  importorg.hibernate.Session;  importorg.hibernate.Transaction;  publicclassHibernateUpdate {  publicstaticvoidmain(String args[]) {  Session sessionObj = HibernateUtil.getSessionFactory().openSession();  introll = 5;  Transaction transactionObj = sessionObj.beginTransaction();  Student studentObj = (Student) session.load(Student.class, roll);  try{  studentObj.setName("Java Code Geek");  studentObj.setCourse("Hibernate");  sessionObj.merge(studentObj);  transactionObj.commit();  System.out.println("Update Successfully");  sessionObj.close();  } catch(HibernateExceptionhibernateEx) {  try{  transactionObj.rollback();  } catch(RuntimeExceptionruntimeEx){  System.err.printf("Couldn’t Roll Back Transaction", runtimeEx);  }  hibernateEx.printStackTrace();  } finally{  if(sessionObj!= null) {  sessionObj.close();  }  }  }  }

Note: Any exceptions thrown by the Hibernate framework are FATAL, hence developers have to rollback the transaction and close the current session object immediately.  



Discussion

No Comment Found