Powered by Blogger.

Wednesday, 9 July 2014

Hibernate Questions

By Shambhu Kumar  |  05:35 No comments




Why Hibernate?
The reasons are plenty, weighing in favor of Hibernate clearly.
  1. Cost effective. Just imagine when you are using EJBs instead of Hibernate. One has to invest in Application Server( Websphere, Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.
  2. The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling. Even less code than JDBC. In fact the OO developers work well when they have to deal with object then writing lousy queries.
  3. High performance then EJBs (if we go by their industry reputation),which itself a container managed, heavyweight solution.
  4. Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.
  5. EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.
What are different fetch strategies Hibernate have?
A fetching strategy in Hibernate is used for retrieving associated objects if the application needs to navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
Hibernate3 defines the following fetching strategies:
  1. Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
  2. Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
  3. Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
  4. Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner is loaded.
  1. Lazy collection fetching - a collection is fetched when the application invokes an operation upon that collection. (This is the default for collections.)
  2. "Extra-lazy" collection fetching - individual elements of the collection are accessed from the database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely needed (suitable for very large collections)
  3. Proxy fetching - a single-valued association is fetched when a method other than the identifier getter is invoked upon the associated object.
  4. "No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed. Compared to proxy fetching, this approach is less lazy (the association is fetched even when only the identifier is accessed) but more transparent, since no proxy is visible to the application. This approach requires buildtime bytecode instrumentation and is rarely necessary.
  5. Lazy attribute fetching - an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.
We use fetch to tune performance. We may use lazy to define a contract for what data is always available in any detached instance of a particular class.

Compare JDBC/DAO with Hibernate?
Hibernate and straight SQL through JDBC are different approaches. They both have their specific significance in different scenarios .
  1. If your application is not to big and complex, not too many tables and queries involved then it will be better to use JDBC. 
  2. While Hibernate is a POJO based ORM tool, using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset ,meaning less LOC but more of configuration work. 
  3. It will suit better when you have large application involving large volume of data and queries. Moreover lazy loading, caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.

What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
  1. Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
  2. Create session factory from configuration object
  3. Get one session from this session factory
  4. Create HQL Query
  5. Execute query to get list containing Java objects
Q. What is a SessionFactory? Is it a thread-safe object?
Answer: SessionFactory is Hibernate’s concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

Creating session Factory in hibernate 4.*
private SessionFactory sessionFactory = null;
// Creating SessionFactory using 4.2 version of Hibernate
Configuration config = new Configuration().configure();
// Build a Registry with our configuration properties
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
// create the session factory
sessionFactory = config.buildSessionFactory(serviceRegistry);

Creating session factory in Hibernate 3.*
sessionFactory = new Configuration().configure().buildSessionFactory();

What role does the SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

What role does the Session interface play in Hibernate?
The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();
Session interface role: 
  1. Wraps a JDBC connection
  2. Factory for Transaction
  3. Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
How to Implement second level cache?
In hibernate.cfg.xml
<property name="cache.use_second_level_cache">true</property>  
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>

In Entity Class
@Entity
@Table(name = "student")
@Cacheable //this annotation is use for enabling cache  
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY) 
public class Student


What’s the difference between load() and 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.

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.

Q. What is the difference between the session.update() method and the session.lock() method?
 Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.

Q. What are the general considerations or best practices for defining your Hibernate persistent classes?
1.      You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables. 
2.      You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
3.      It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.      The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.      Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

Question: What happens when both hibernate.properties and hibernate.cfg.xmlare in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.

Question: What methods must the persistent classes implement in Hibernate?
Answer: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.

Question: What are derived properties?
Answer: 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. Ex:- If firstName and lastName is field then we can just write one method 
  getFullName(){ return firstName+" "+lastName()}

Question: How can you make a property be read from the database but not modified in anyway (make it immutable)?
Answer: Use insert="false" and update="false" attributes.

Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.

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

What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
  1. HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.
  2. Common functions are simplified to single method calls.
  3. Sessions are automatically closed.
  4. Exceptions are automatically caught and converted to runtime exceptions.
Why to use HQL?
  • Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
  • Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This eliminates the need of creating the object and populating the data from result set.
  • Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.
  • Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.
  • Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
  • Database independent: Queries written in HQL are database independent (If database supports the underlying feature).
Does Hibernate implement its functionality using a minimal number of database queries to ensure optimal output?
Hibernate can make certain optimizations all the time:
  • Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
  • Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
  • Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
  • Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
  • Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
  • Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
  • Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
  • Lazy collection initialization
  • Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.

Q. When does an object become detached?
A.
Session session1 = sessionFactory.openSession();
//myCar is a persistent object at this stage.
Car myCar = session1.get(Car.class, carId); 
//once the session is closed myCar becomes a detached object
session1.close();                              

you can now pass the myCar object all the way upto the presentation tier. It can be modified without any effect to your database table.


 //no effect on the database
myCar.setColor(“Red”);    

When you are ready to persist this change to the database, it can be reattached to another session as shown below:
Session session2 = sessionFactory.openSession();
Transaction tx = session2.beginTransaction();
session2.update(myCar); //detached object myCar gets re-attached
tx.commit();            //change is synchronized with the database.
session2.close();

Q. Explain hibernate object states? Explain hibernate objects life cycle?
A.
Persistent objects and collections are short lived single threaded objects, which store the persistent state. These objects synchronize their state with the database depending on your flush strategy (i.e. auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List  etc or define your own synchronization points with session.flush(), transaction.commit() calls). If you remove an item from a persistent collection like a Set, it will be removed from the database either immediately or when flush() or commit() is called depending on your flush strategy. They are Plain Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated session is closed, persistent objects become detached objects and are free to use directly as data transfer objects in any application layers like business layer, presentation layer etc.  

Detached objects and collections are instances of persistent objects that were associated with a session but currently not associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Detached objects can be later on attached to another session by calling methods like session.update(), session.saveOrUpdate() etc. and become persistent objects.

Transient objects and collections are instances of persistent objects that were never associated with a session. These objects can be freely used as Data Transfer Objects without having any impact on your database. Transient objects become persistent objects when associated to a session by calling methods like session.save( ), session.persist( )  etc.
Q. What are the benefits of detached objects?
A.
Pros:
  • When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons:
  • In general, working with detached objects is quite cumbersome, and it is better not to clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.
  • Also from pure rich domain driven design perspective, it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.
 Difference between JDBC and hibernate
  1. Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific.
  2. As Hibernate is set of Objects, you don’t need to learn SQL language. You can treat TABLE as an Object. Only Java knowledge is need. In case of JDBC you need to learn SQL.
  3. Don’t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.In case of JDBC you need to tune your queries.
  4. You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.In case of JDBC you need to implement your java cache.
  5. Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics.
  6. Development fast in case of Hibernate because you don’t need to write queries 
  7. No need to create any connection pool in case of Hibernate. You can use c3p0.  In case of JDBC you need to write your own connection pool
  8. In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
  9. You can load your objects on start up using lazy=false in case of Hibernate. JDBC Don’t have such support.
  10. Hibernate Supports automatic versioning of rows but JDBC Not.


What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.
  1. dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
  2. dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

How can Hibernate be configured to access an instance variable directly and not through a setter method ?
By mapping the property with access="field" in Hibernate metadata. These forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.




























Author: Shambhu Kumar

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP