Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Monday 5 December 2016

Hibernate Interview Questions Part 2

1.What is the difference between load() and get()?
load() vs. get() :-
load() get() 
Only use the load() method if you are sure that the object exists. If you are not sure that the object exists, then use one of the get() methods. 
load() method will throw an exception if the unique id is not found in the database. get() method will return null if the unique id is not found in the database. 
load() just returns a proxy by default and database won�t be hit until the proxy is first invoked.  get() will hit the database immediately. 

2.What is the difference between and merge and update ?
Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

3.How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
<id column="USER_ID" name="id" type="java.lang.Long"> 
   <generator class="sequence"> 
     <param name="table">SEQUENCE_NAME</param>
   <generator>
</id>

4.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

5.What do you mean by Named � SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
<sql-query name = "empdetails">
   <return alias="emp" class="com.test.Employee"/>
      SELECT emp.EMP_ID AS {emp.empid},
                 emp.EMP_ADDRESS AS {emp.address},
                 emp.EMP_NAME AS {emp.name} 
      FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>

Invoke Named Query :
List people = session.getNamedQuery("empdetails")
       .setString("TomBrady", name)
       .setMaxResults(50)
       .list();

6.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true">
 <return alias="emp" class="employee">
   <return-property name="empid" column="EMP_ID"/>       

   <return-property name="name" column="EMP_NAME"/>       
   <return-property name="address" column="EMP_ADDRESS"/>
    { ? = call selectAllEmployees() }
 </return>
</sql-query>



7.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
           .add(Restrictions.like("name", "a%") )
           .add(Restrictions.like("address", "Boston"))
    .addOrder(Order.asc("name") )
    .list();

8.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

9.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
  • HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  • Common functions are simplified to single method calls.
  • Sessions are automatically closed.
  • Exceptions are automatically caught and converted to runtime exceptions.

10.How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

11.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>

12.What are derived properties?
The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

13.What is component mapping in Hibernate?
  • A component is an object saved as a value, not as a reference
  • A component can be saved directly without needing to declare interfaces or identifier properties
  • Required to define an empty constructor
  • Shared references not supported
Example:
Component Mapping

14.What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-

sorted collection order collection 
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. 
If your collection is not large, it will be more efficient way to sort it.

source:http://www.developersbook.com/
If your collection is very large, it will be more efficient way to sort it . 

Monday 21 November 2016

Hibernate 4.3 Introduction Tutorial

An introduction to Hibernate 4

In this article I will show you how can you use Hibernate 4,  along with a simple example application available to try out what you read about.




What is Hibernate and why should I care?

Hibernate was created to leverage the connection between Java applications and relational databases because it is hard to map back and forth between a database table and a Java object.
And because Hibernate does this, it reduces development time which is consumed by JDBC query-execution and data mapping.

Getting Hibernate

To get the latest version of Hibernate, just visit this site. For this article I will use the version 4.3.10.Final.
If you download and extract the package you can see some sub-folders in the lib folder. Everything under required is required for any project using Hibernate. The other folders contain libraries for special cases. For example under jpa you find the library providing the JPA entity manager support.
Alternatively you can set up a Maven project and add Hibernate as a dependency. In this case you do not need to take care about the other required dependencies of Hibernate, which come along in the required package with the bundle-download. Using Maven is more simple and straightforward so I will use Maven as dependency management.

A simple example

In the simple example I will create a Java application which stores information about books in the database. The database will be an H2 memory database for the sake of simplicity.
Dependencies are managed with Maven and the output is an executable JAR with all dependencies.

The entity

The entity I will store in the database is the following:
The no-argument constructor is a requirement for all persistent classes because Hibernate creates the object instances per reflection. In this case this constructor is private to prevent creation of books without information.

The dependencies

To get the app running, we need two dependencies in the project: Hibernate and H2. To do this, add the following to the pom.xml:
Now we are ready to continue on.

Configuring Hibernate

Hibernate needs some configuration to get started. This you need to include in the hibernate.cfg.xml file. It is plain old XML. It contains the database connection properties and the entity mapping files inclusive location.

The entity mapping

To map the right fields to the right column in the database, Hibernate requires a mapping file for the entities. These are located in the .hbm.xml files which start with the entity’s name. In this example Book.hbm.xml.

The main method

To use the application with Hibernate we still need an entry point — and in Java this is the main method. To start, we need some configuration, like creating a session with a session factory… So let’s look at the code how it goes:

After running the application the console should have some log messages and the one book added to the database:
—-
—–

Conclusion

Hibernate gives a nice feature to leverage mapping between Java objects and relational databases. Naturally this sample application does not show the full power of Hibernate: for better user experience you could add a user interface to create and list books in the application.
In a later article I will show how to get rid of the XML configuration (called by some developers as the “XML-Hell”) and use annotations instead. So stay tuned.

Source:javabeginnerstutorial.co