Hibernate :
Links: http://java-dvlpr.blogspot.in/p/hibernate-interview-questionshibernate.html
What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
What are the important tags of hibernate.cfg.xml?
Figure out from the above hibernate-cfg.xml file.
What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
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.
What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database.
What is the difference between 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.
How do you define sequence generated primary key in hibernate?
Using <generator> tag.
Example:-
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?
What does it mean to be inverse?
It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.
What do you mean by Named – SQL query?
Named SQL queries are defined in the mapping xml document and called wherever required.
Example:
How do you invoke Stored Procedures?
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 :
What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.
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. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object
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.
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.
What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
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 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 are the types of Hibernate instance states ?
Three types of instance states:
What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :-
What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
What is a pure relational ORM?
What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.
What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.
What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.
How to access multiple database in hibernate?
Creating two/multiple XML configuration files and creating two/Multiple Configuration and Session Factory objects in the application to connect two/multiple databases can achieve this.
Configuration cfg_oracle = new Configuration().configure("hibernate_oracle.cfg.xml");
Configuration cfg_mysql = new Configuration().configure("hibernate_mysql.cfg.xml");
What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
What the Core interfaces are of hibernate framework?
What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
What do you create a SessionFactory?
What does hibernate.properties file consist of?
This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.
What should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.
What are POJOs?
POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.
What is object/relational mapping metadata?
ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.
What is HQL?
HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.
What are the different types of property and class mappings?
What is Attribute Oriented Programming?
XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.
What are the different methods of identifying an object?
There are three methods by which an object can be identified.
What are different caches supported by Hibernate?
Hibernate uses two different caches for objects: first-level cache and second-level cache..
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces thenumber of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.
Caches Supported in ?
Difference between session.save() , session.saveOrUpdate() and session.persist()?
Hibernate VsJDBC?
How to prevent concurrent update in Hibernate?
Q.Difference between session.update() and session.lock() in Hibernate ?
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.
Difference between getCurrentSession() and openSession() in Hibernate ?
Difference between session.saveOrUpdate() and session.merge()?
<b>saveOrUpdate() </b>does the following:
? if the object is already persistent in this session, do nothing
? if another object associated with the session has the same identifier, throw an exception
? if the object has no identifier property, save() it
? if the object's identifier has the value assigned to a newly instantiated object, save() it
? if the object is versioned (by a <version> or <timestamp>), and the version property value is the same
value assigned to a newly instantiated object, save() it
? otherwise update() the object
<b>merge() </b>is very different:
? if there is a persistent instance with the same identifier currently associated with the session, copy the state
of the given object onto the persistent instance
? if there is no persistent instance currently associated with the session, try to load it from the database, or
create a new persistent instance
? the persistent instance is returned
? the given instance does not become associated with the session, it remains detached
Precisely:
void saveOrUpdate(object)->object must be attached to a hibernate session (including all sub objects within the object), and once save/update is done, the object reflects the updated changes (e.g. primary key if saving a new object)
�
Object merge(object)-> object does not have to be attached to a hibernate session. Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session.
Difference between list() and iterate() i9n Hibernate?
If instances are already be in the session or second-level cache iterate() will give better performance.
If they are not already cached, iterate() will be slower
than list() and might require many database hits for a simple query.
One To Many Bi-directional Relation in Hibernate?
What does session.refresh() do ?
It is possible to re-load an object and all its collections at any time, using the refresh() method. This is useful
when database triggers are used to initialize some of the properties of the object.
For Example - Triger on cat_name coulmn. Trigger is updating hit_count coulmn in the same Cat Table. When Insert data into Cat TABLE trigger update hit_count coulmn to 1. sess.refresh() reload all the data. No nned again to select call.
sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)
How to set 2nd level cache in hibernate with EHCache?
When you are creating SessionFactory just add the below steps
String ecache = appHome+File.separatorChar+"ehcache.xml";
try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/
Then
sessionFactory = configuration.buildSessionFactory();
ECache.xml is like
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="bean.ApplicationBean"
maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>
</ehcache>
ApplicationBean will be avilable in 2nd level cache
How are joins handled using Hinernate.
Best is use Criteria query
Example -
You have parent class
public class Organization {
private long orgId;
private List messages;
}
Child class
public class Message {
private long messageId;
private Organization organization;
}
.hbm.xml file
<class name="com.bean.Organization" table="ORGANIZATION">
<bag name="messages" inverse="true" cascade="delete" lazy="false">
<key column="MSG_ID" />
<one-to-many
class="com.bean.Message" />
</bag>
</class>
<class name="com.bean.Message" table="MESSAGE">
<many-to-one name="organization" column="ORG_ID" lazy="false"/>
</class>
Get all the messages from message table where organisation id = <any id>
Criteria query is :
session.createCriteria(Message.class).createAlias("organization","org").
add(Restrictions.eq("org.orgId",new Long(orgId))).add(Restrictions.in("statusCode",status)).list();
How to Execute Stored procedure in Hibernate ?
<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>
code :
SQLQuery sq = (SQLQuery) session.getNamedQuery("selectAllEmployees_SP");
List results = sq.list();
Q. What is lazy loading and how do you achieve that in hibernate?
A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.
Q. What are the different fetching strategy in Hibernate?
A. Hibernate3 defines the following fetching strategies:
A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache andsecond-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:
Q. What are the different caching strategies?
A. The following four caching strategies are available:
Q. How do you configure 2nd level cach in hibernate?
A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: <hibernate-configuration>
<session-factory>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
</session-factory>
</hibernate-configuration>
By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.
Q. What is the difference between sorted and ordered collection in hibernate?
A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
Q. What are the types of inheritence models and describe how they work like vertical inheritence and horizontal?
A. There are three types of inheritance mapping in hibernate :
2. What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.
To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below:
Read more at http://www.gointerviews.com/hibernate-interview-questions/#Dj5aBil51RBfD6lv.99
19) What do
you create a SessionFactory?
20) What is
meant by Method chaining?
21) What
does hibernate.properties file consist of?
22) What
should SessionFactory be placed so that it can be easily accessed?
23) What are
POJOs?
24) What is
object/relational mapping metadata?
25) What is
HQL?
26) What are
the different types of property and class mappings?
27) What is
Attribute Oriented Programming?
28) What are
the different methods of identifying an object?
29) What are
the different approaches to represent an inheritance hierarchy?
30) What are
managed associations and hibernate associations?
The ehcache.xml can be configured to cache objects of type com.myapp.Order as shown below
second-level cache reduces the database traffic by caching loaded objects at the SessionFactory level between transactions. These objects are available to the whole application, not just to the user running the query. The 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached. It is imperative to implement proper cache expiring strategies as caches are never aware of changes made to the persistent store by another application. he following are the list of possible cache strategies.
It can be enabled via the Hibernate mapping files as shown below:
Note: The usage options are: transactional|read-write|nonstrict-read-write|read-only. The cache can also be enabled at different granular level (e.g. parent, children, etc). The active orders will be cached for 300 seconds.
-->
Q. How does the hibernate second-level cache work?
A. Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database. Hibernate's static initialize() method, which populates a proxy object, will attempt to hit the second-level cache before going to the database. The Hibernate class provides static methods for manipulation of proxies.
As a consequence of using the Hibernate second-level cache, you have to be aware of the fact that each call of a data access method can either result in a cache hit or miss. So, configure your log4j.xml to log your hits and misses.
Alternatively, you can use Spring AOP to log the cache access on your DAO methods.
The second level cache is a powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtle in their behavior. Especially, the interaction with the Hibernate session can lead to unwanted behavior.
Q. What is a query cache in Hibernate?
A. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries. Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.
You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.
<property name="hibernate.cache.use_query_cache">true</property>
Q. What are the pitfalls of second level and query caches?
A. Memeory is a finite resource, and over use or incorrect useage like cacheing the Order object and all its referenced objects can cause OutOfMemoryError. Here are some tips to overcome the pitfalls relating to cacheing.
1. Set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters. Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.
In the example below, the entire customer and everything he/she references would be held in cache until either the query cache exceeds its configured limits and it is evicted, or the table is modified and the results become dirty.
Instead of setting the whole customer object as shown above, just set the id.
2. Hibernate's query cache implementation is pluggable by decorating Hibernate's query cache implementation. This involves overriding the put( ) method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists.
3. If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.
Here are some general performance tips:
1. Session.load will always try to use the cache. Session.find does not use the cache for the primary object, but cause the cache to be populated. Session.iterate always uses the cache for the primary object and any associated objects.
2. While developing, enable the show SQL and monitor the generated SQL.
<property name="show_sql">true</property>
Also enable the "org.hibernate.cache" logger in your log4j.xml to monitor cache hits and misses.
Quality Center is a comprehensive test management tool. It is a web-based tool
and supports high level of communication and association among various
stakeholders (Business Analyst, Developers , Testers etc. ) , driving a more
effective and efficient global application-testing process. Automation Tools
like QTP , WinRunner & LoadRunner can be integrated with Quality Center .
One can also create reports and graphs for Analysis and Tracking for Test
processes.
Links: http://java-dvlpr.blogspot.in/p/hibernate-interview-questionshibernate.html
What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
What does ORM consists of ?
An ORM solution consists of the following four pieces:
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
What does ORM consists of ?
An ORM solution consists of the following four pieces:
- API for performing basic CRUD operations
- API to express queries referring to classes
- Facilities to specify metadata
What are the ORM levels ?
The ORM levels are:
The ORM levels are:
- Pure relational (stored procedure.)
- Light objects mapping (JDBC)
- Medium object mapping
- Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
Hibernate object Life cycle:
By looking into the below pic, we can understand better how an object is handled by Hibernate for user operations. Also, it lists the major hibernate methods that we use in a typical application.
What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
Hibernate Vs. JDBC :-
JDBC |
Hibernate
|
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.
|
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
|
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.
|
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
|
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.
|
Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
|
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table.
|
Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
|
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.
|
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
|
With JDBC, caching is maintained by hand-coding.
|
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
|
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.
|
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.
|
Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
- Improved productivity
- High-level object-oriented API
- Less Java code to write
- No SQL to write
- Improved performance
- Sophisticated caching
- Lazy loading
- Eager loading
- Improved maintainability
- A lot less code to write
- Improved portability
- ORM framework generates database-specific SQL for you
What Does Hibernate Simplify?
Hibernate simplifies:
Hibernate simplifies:
- Saving and retrieving your domain objects
- Making database column and table name changes
- Centralizing pre save and post retrieve logic
- Complex joins for retrieving related items
- Schema creation from object model
What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/garnaik</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="show_sql">true</property>
<mapping resource="com/garnaik/classified/pojo/Department.hbm.xml"/>
<mapping resource="com/garnaik/classified/pojo/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/garnaik</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="show_sql">true</property>
<mapping resource="com/garnaik/classified/pojo/Department.hbm.xml"/>
<mapping resource="com/garnaik/classified/pojo/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
- Programmatic configuration
- XML configuration (hibernate.cfg.xml)
What are the important tags of hibernate.cfg.xml?
Figure out from the above hibernate-cfg.xml file.
What are the Core interfaces are of Hibernate framework?
The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.
- Session interface
- SessionFactory interface
- Configuration interface
- Transaction interface
- Query and Criteria interfaces
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:
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:
- Wraps a JDBC connection
- Factory for Transaction
- Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier
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
SessionFactory sessionFactory = configuration.buildSessionFactory()
SessionFactory sessionFactory = configuration.buildSessionFactory()
What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
- Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
- Create session factory from configuration object
- Get one session from this session factory
- Create HQL Query
- Execute query to get list containing Java objects
What is Hibernate Query Language (HQL)?
Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database.
This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.
How do you map Java Objects with Database tables?
How do you map Java Objects with Database tables?
- First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
- Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
What’s the difference between load() and get()?
load() vs. 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.
|
What is the difference between 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.
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>
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?
What does it mean to be inverse?
It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.
How many ways we can execute queries in Hibernate?
Four different ways
1. HQL (session.createQuery())
2. Criteria (session.createCriteria())
3. Named query (session.getNamedQuery())
4. SQL Query (session.createSQLQuery())
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();
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>
Ex:
my mapping file is
<sql-query name="book_testing" callable="true">
<return alias="book" class="Book">
<return-property name="lngBookId" column="id" />
<return-property name="strBookName" column="bookname" />
</return>
{ call book_return( ?,:lngBookId) }
</sql-query>
my program is
List ls = session.getNamedQuery("book_testing")
.setInteger("lngBookId",4)
.list();
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();
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.
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.
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.
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.
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>
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.
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
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>
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.
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
What is the difference between sorted and ordered collection in hibernate?
sorted collection vs. order collection :-
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.
|
If your collection is very large, it will be more efficient way to sort it .
|
32.What are the Collection types in Hibernate ?
- Bag
- Set
- List
- Array
- Map
33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
- An implicit association join
- An ordinary join in the FROM clause
- A fetch join in the FROM clause.
- A theta-style join in the WHERE clause.
What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.
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. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object
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.
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.
- dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed
- dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
1. fetch-”join” = Disable the lazy loading, always load all the collections and entities.
2. fetch-”select” (default) = Lazy load all the collections and entities.
3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
4. fetch-”subselect” = Group its collection into a sub select statement.
2. fetch-”select” (default) = Lazy load all the collections and entities.
3. batch-size=”N” = Fetching up to ‘N’ collections or entities, *Not record*.
4. fetch-”subselect” = Group its collection into a sub select statement.
What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.
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 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 are the types of Hibernate instance states ?
Three types of instance states:
- Transient -The instance is not associated with any persistence context
- Persistent -The instance is associated with a persistence context
- Detached -The instance was associated with a persistence context which has been closed – currently not associated
What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :-
Hibernate |
EJB 3.0
|
Session–Cache or collection of loaded objects relating to a single unit of work
|
Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
|
XDoclet Annotations used to support Attribute Oriented Programming
|
Java 5.0 Annotations used to support Attribute Oriented Programming
|
Defines HQL for expressing queries to the database
|
Defines EJB QL for expressing queries
|
Supports Entity Relationships through mapping files and annotations in JavaDoc
|
Support Entity Relationships through Java 5.0 annotations
|
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API
|
Provides and Entity Manager Interface for managing CRUD operations for an Entity
|
Provides callback support through lifecycle, interceptor, and validatable interfaces
|
Provides callback support through Entity Listener and Callback methods
|
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships
|
Entity Relationships are bidirectional or unidirectional
|
What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
- Table per class hierarchy
- Table per subclass
- Table per concrete class
Lazy Loading and Eager Loading
In default, Hibernate adopts the mechanism of lazy loading to load objects from databases. Lazy loading contributes a lot to improve the performance of an application by limiting the amount of objects that will be needed. In contrast to lazy loading, eager loading loads the full objects tree once. Because eager loads multiple related objects with a single SELECT statement instead of using multiple SELECT statements, therefore in some situations, eager loads can also improve the performance of the application by reducing the times of accessing the database.
There are two ways to configure eager loading in Hibernate. They are staticly eager loading and dynamically eager loading respectively. If the application always traverses a relationship, you might want to configure it to be always staticly eager loaded. Conversely, you might want to dynamically configure eager loading for relationships that are only traversed by the application when handling particular requests.
One way to configure static eager loading is specifying a value for the fetch attribute of the relationship’s mapping element.
This attribute can have one of two values:
select: Lazily load the referenced object or collection with a separate SQL SELECT statement. It is the default value
join: Eagerly load the referenced object or collection using an outer join.
One way to configure static eager loading is specifying a value for the fetch attribute of the relationship’s mapping element.
This attribute can have one of two values:
select: Lazily load the referenced object or collection with a separate SQL SELECT statement. It is the default value
join: Eagerly load the referenced object or collection using an outer join.
what is lazy fetching in hibernate?
There are two types of Loading in application. Eager loading and Lazy loading. In eager loading we will fetch all the values from the Persistent storage and cache it. It will make serious performance issues. There we use lazy loading to avoid that scenario.
Some times we don't need to load the child table values, In that case we have to us lazy = true in .hbm file. so hibernate will fetch only parent table values. Internally it will load the wrapper class but it does not cache all the values till we perform operation.
Main Advantage: It will avoid caching unnecessary values and improve performances.
Disadvantage is LazyInitialization exception happens when the session is not available and a lazily associated is accesed.
Some times we don't need to load the child table values, In that case we have to us lazy = true in .hbm file. so hibernate will fetch only parent table values. Internally it will load the wrapper class but it does not cache all the values till we perform operation.
Main Advantage: It will avoid caching unnecessary values and improve performances.
Disadvantage is LazyInitialization exception happens when the session is not available and a lazily associated is accesed.
What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.
What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.
What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.
What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.
How to access multiple database in hibernate?
Creating two/multiple XML configuration files and creating two/Multiple Configuration and Session Factory objects in the application to connect two/multiple databases can achieve this.
Configuration cfg_oracle = new Configuration().configure("hibernate_oracle.cfg.xml");
Configuration cfg_mysql = new Configuration().configure("hibernate_mysql.cfg.xml");
What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="sample.MyPersistanceClass" table="MyPersitaceTable"> <id name="id" column="MyPerId"> <generator class="increment"/> </id> <property name="text" column="Persistance_message"/> <many-to-one name="nxtPer" cascade="all" column="NxtPerId"/> </class> </hibernate-mapping> |
Everything should be included under <hibernate-mapping> tag. This is the main tag for an xml mapping document.
What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important one.
- Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
- SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
- Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
- Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
- Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.
What are Extension interfaces?
When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.
What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
- ProxyFactory interface - used to create proxies
- ConnectionProvider interface – used for JDBC connection management
- TransactionFactory interface – Used for transaction management
- Transaction interface – Used for transaction management
- TransactionManagementLookup interface – Used in transaction management.
- Cahce interface – provides caching techniques and strategies
- CacheProvider interface – same as Cache interface
- ClassPersister interface – provides ORM strategies
- IdentifierGenerator interface – used for primary key generation
- Dialect abstract class – provides SQL support
What are different environments to configure hibernate?
There are mainly two types of environments in which the configuration of hibernate application differs.
There are mainly two types of environments in which the configuration of hibernate application differs.
- Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
- Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.
What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.
What do you create a SessionFactory?
Configuration cfg = new Configuration(); cfg.addResource("myinstance/MyConfig.hbm.xml"); cfg.setProperties( System.getProperties() ); SessionFactory sessions = cfg.buildSessionFactory(); |
First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().
What is meant by Method chaining?
What is meant by Method chaining?
Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.
SessionFactory sessions = new Configuration() .addResource("myinstance/MyConfig.hbm.xml") .setProperties( System.getProperties() ) .buildSessionFactory(); |
What does hibernate.properties file consist of?
This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect |
What should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.
What are POJOs?
POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.
What is object/relational mapping metadata?
ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.
What is HQL?
HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.
What are the different types of property and class mappings?
- Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
Or <property name="description" type="string"> <column name="DESCRIPTION"/> </property> |
- Derived properties
<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>
|
- Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
|
- Controlling inserts and updates
<property name="name" column="NAME" type="string"
insert="false" update="false"/> |
What is Attribute Oriented Programming?
XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.
What are the different methods of identifying an object?
There are three methods by which an object can be identified.
- Object identity –Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
- Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.
- Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.
What are the different approaches to represent an inheritance hierarchy?
- Table per concrete class.
- Table per class hierarchy.
- Table per subclass.
What are managed associations and hibernate associations?
Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.
What are different caches supported by Hibernate?
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces thenumber of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.Caches Supported in ?
EHCache
JBOSS Cache
OSCache
SwarmCache
What are the caching strategies?
1. Read-only
2. Read –write
3. Nonstrict read-write
4. Transactional
Difference between session.save() , session.saveOrUpdate() and session.persist()?
session.save() : Save does an insert and will fail if the primary key is already persistent.
session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.
Insert data if primary key not exist otherwise update data.
session.persist() : Does the same like session.save().
But session.save() return Serializable object but session.persist() return void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.
For Example :
if you do :-
System.out.println(session.save(question));
This will print the generated primary key.
if you do :-
System.out.println(session.persist(question));
Compile time error because session.persist() return void.
session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update.
Insert data if primary key not exist otherwise update data.
session.persist() : Does the same like session.save().
But session.save() return Serializable object but session.persist() return void.
session.save() returns the generated identifier (Serializable object) and session.persist() doesn't.
For Example :
if you do :-
System.out.println(session.save(question));
This will print the generated primary key.
if you do :-
System.out.println(session.persist(question));
Compile time error because session.persist() return void.
Hibernate VsJDBC?
There are so many
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 a 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 wth 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.
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 a 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 wth 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.
How to prevent concurrent update in Hibernate?
version checking used in hibernate when more then one thread trying to access same data.
Declare a variable "versionId" in your Class with setter and getter.
In the .hbm.xml file
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
<id name="campignId" type="long" column="cid">
<generator class="sequence">
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId" type="long" column="version" />
<property name="name" column="c_name"/>
</class>
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
<id name="campignId" type="long" column="cid">
<generator class="sequence">
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId" type="long" column="version" />
<property name="name" column="c_name"/>
</class>
Create a coulmn name "version" in the CAMPIGN table.
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();
You can handle StaleObjectStateException() and do what ever you want.
You can display error message.
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();
You can handle StaleObjectStateException() and do what ever you want.
You can display error message.
Q.Difference between session.update() and session.lock() in Hibernate ?
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.
Difference between getCurrentSession() and openSession() in Hibernate ?
getCurrentSession() :
The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.
A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends.
It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.
The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.
A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends.
It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs.
Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically.
openSession() :
If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and close() it.
It does not flush and close() automatically.
If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and close() it.
It does not flush and close() automatically.
Difference between session.saveOrUpdate() and session.merge()?
<b>saveOrUpdate() </b>does the following:
? if the object is already persistent in this session, do nothing
? if another object associated with the session has the same identifier, throw an exception
? if the object has no identifier property, save() it
? if the object's identifier has the value assigned to a newly instantiated object, save() it
? if the object is versioned (by a <version> or <timestamp>), and the version property value is the same
value assigned to a newly instantiated object, save() it
? otherwise update() the object
<b>merge() </b>is very different:
? if there is a persistent instance with the same identifier currently associated with the session, copy the state
of the given object onto the persistent instance
? if there is no persistent instance currently associated with the session, try to load it from the database, or
create a new persistent instance
? the persistent instance is returned
? the given instance does not become associated with the session, it remains detached
Precisely:
void saveOrUpdate(object)->object must be attached to a hibernate session (including all sub objects within the object), and once save/update is done, the object reflects the updated changes (e.g. primary key if saving a new object)
�
Object merge(object)-> object does not have to be attached to a hibernate session. Once save/update is done, the object DOES NOT reflect the change. The returned object reflects the changes, and it is attached to hibernate session.
Difference between list() and iterate() i9n Hibernate?
If instances are already be in the session or second-level cache iterate() will give better performance.
If they are not already cached, iterate() will be slower
than list() and might require many database hits for a simple query.
One To Many Bi-directional Relation in Hibernate?
<class name="com.bean.ProcessBean"
table="PROCESS">
<id name="processId" type="long" column="PROCESS_ID" />
<property name="processName" column="PROCESS_NAME" type="string"
length="50" />
<many-to-one name="processType" column="PROCESS_TYPE_ID" lazy="false" />
</class>
<class name="com.bean.ProcessTypeBean"
table="PROCESS_TYPE_LOV">
<id name="processTypeId" type="long" column="PROCESS_TYPE_ID" />
<property name="processTypeName" column="PROCESS_TYPE_NAME"
type="string" length="50" />
<bag name="processes" inverse="true" cascade="delete" lazy="false">
<key column="PROCESS_TYPE_ID" />
<one-to-many
class="com.bean.ProcessBean" />
</bag> </class>
table="PROCESS">
<id name="processId" type="long" column="PROCESS_ID" />
<property name="processName" column="PROCESS_NAME" type="string"
length="50" />
<many-to-one name="processType" column="PROCESS_TYPE_ID" lazy="false" />
</class>
<class name="com.bean.ProcessTypeBean"
table="PROCESS_TYPE_LOV">
<id name="processTypeId" type="long" column="PROCESS_TYPE_ID" />
<property name="processTypeName" column="PROCESS_TYPE_NAME"
type="string" length="50" />
<bag name="processes" inverse="true" cascade="delete" lazy="false">
<key column="PROCESS_TYPE_ID" />
<one-to-many
class="com.bean.ProcessBean" />
</bag> </class>
What does session.refresh() do ?
It is possible to re-load an object and all its collections at any time, using the refresh() method. This is useful
when database triggers are used to initialize some of the properties of the object.
For Example - Triger on cat_name coulmn. Trigger is updating hit_count coulmn in the same Cat Table. When Insert data into Cat TABLE trigger update hit_count coulmn to 1. sess.refresh() reload all the data. No nned again to select call.
sess.save(cat);
sess.flush(); //force the SQL INSERT
sess.refresh(cat); //re-read the state (after the trigger executes)
How to set 2nd level cache in hibernate with EHCache?
When you are creating SessionFactory just add the below steps
String ecache = appHome+File.separatorChar+"ehcache.xml";
try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/
Then
sessionFactory = configuration.buildSessionFactory();
ECache.xml is like
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="bean.ApplicationBean"
maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>
</ehcache>
ApplicationBean will be avilable in 2nd level cache
How are joins handled using Hinernate.
Best is use Criteria query
Example -
You have parent class
public class Organization {
private long orgId;
private List messages;
}
Child class
public class Message {
private long messageId;
private Organization organization;
}
.hbm.xml file
<class name="com.bean.Organization" table="ORGANIZATION">
<bag name="messages" inverse="true" cascade="delete" lazy="false">
<key column="MSG_ID" />
<one-to-many
class="com.bean.Message" />
</bag>
</class>
<class name="com.bean.Message" table="MESSAGE">
<many-to-one name="organization" column="ORG_ID" lazy="false"/>
</class>
Get all the messages from message table where organisation id = <any id>
Criteria query is :
session.createCriteria(Message.class).createAlias("organization","org").
add(Restrictions.eq("org.orgId",new Long(orgId))).add(Restrictions.in("statusCode",status)).list();
How to Execute Stored procedure in Hibernate ?
<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>
code :
SQLQuery sq = (SQLQuery) session.getNamedQuery("selectAllEmployees_SP");
List results = sq.list();
Q. What is lazy loading and how do you achieve that in hibernate?
A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.
Q. What are the different fetching strategy in Hibernate?
A. Hibernate3 defines the following fetching strategies:
Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN.
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.
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.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.
For more details read short primer on fetching strategy at http://www.hibernate.org/315.html
Q. What are different types of cache hibernate supports ?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.
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.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.
For more details read short primer on fetching strategy at http://www.hibernate.org/315.html
A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache andsecond-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:
EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
Commercial Tangosol Coherence cache.
Q. What are the different caching strategies?
A. The following four caching strategies are available:
Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
Transactional: This is a fully transactional cache that may be used only in a JTA environment.
Q. How do you configure 2nd level cach in hibernate?
A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: <hibernate-configuration>
<session-factory>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
</session-factory>
</hibernate-configuration>
By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.
Q. What is the difference between sorted and ordered collection in hibernate?
A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
Q. What are the types of inheritence models and describe how they work like vertical inheritence and horizontal?
A. There are three types of inheritance mapping in hibernate :
Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker
1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1. What’s Hibernate?
Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.
2. What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API’s to perform different types of operations on the data tables.
3. How properties of a class are mapped to the columns of a database table in Hibernate?
Mappings between class properties and table columns are specified in XML file as in the below example:
4. What’s the usage of Configuration Interface in hibernate?
Configuration interface of hibernate framework is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.
5. How can we use new custom interfaces to enhance functionality of built-in interfaces of hibernate?
We can use extension interfaces in order to add any required functionality which isn’t supported by built-in interfaces.
6. Should all the mapping files of hibernate have .hbm.xml extension to work properly?
No, having .hbm.xml extension is a convention and not a requirement for hibernate mapping file names. We can have any extension for these mapping files.
7. How do we create session factory in hibernate?
To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below:
[java]
Configuration config = new Configuration();
config.addResource(&quot;myinstance/configuration.hbm.xml&quot;);
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();
Configuration config = new Configuration();
config.addResource(&quot;myinstance/configuration.hbm.xml&quot;);
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();
[/java]
8. What are POJOs and what’s their significance?
POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.
9. What’s HQL?
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.
10. How can we invoke stored procedures in hibernate?
In hibernate we can execute stored procedures using code as below:
In hibernate we can execute stored procedures using code as below:
[xml]
<sql-query name=”getStudents” callable=”true”>
<return alias=”st” class=”Student”>
<return-property name=”std_id” column=”STD_ID”/>
<return-property name=”s_name” column=”STD_NAME”/>
<return-property name=”s_dept” column=”STD_DEPARTMENT”/>
{ ? = call selectStudents() }
</return>
</sql-query>
<return alias=”st” class=”Student”>
<return-property name=”std_id” column=”STD_ID”/>
<return-property name=”s_name” column=”STD_NAME”/>
<return-property name=”s_dept” column=”STD_DEPARTMENT”/>
{ ? = call selectStudents() }
</return>
</sql-query>
[/xml]
11. What is criteria API?
Criteria is a simple yet powerful API of hibernate which is used to retrieve entities through criteria object composition.
12. What are the benefits of using Hibernate template?
Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.
Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.
13. How can we see hibernate generated SQL on console?
We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:
We need to add following in hibernate configuration file to enable viewing SQL on the console for debugging purposes:
[xml]
<property name=”show_sql”>true</property>
[/xml]
14. What are the two types of collections in hibernate?
Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection
Following are the two types of collections in hibernate:
a. Sorted Collection
b. Order Collection
15. What’s the difference between session.save() and session.saveOrUpdate() methods in hibernate?
Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.
Sessionsave() method saves a record only if it’s unique with respect to its primary key and will fail to insert if primary key already exists in the table.
saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.
16. What the benefits are of hibernate over JDBC?
a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.
a. Hibernate can be used seamlessly with any type of database as its database independent while in case of JDBC, developer has to write database specific queries.
b. Using hibernate, developer doesn’t need to be an expert of writing complex queries as HQL simplifies query writing process while in case of JDBC, its job of developer to write and tune queries.
c. In case of hibernate, there is no need to create connection pools as hibernate does all connection handling automatically while in case of JDBC, connection pools need to be created.
17. How can we get hibernate statistics?
We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()
We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:
SessionFactory.getStatistics()
18. What is transient instance state in Hibernate?
If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.
If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it’s said to be in transient state.
19. How can we reduce database write action times in Hibernate?
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.
20. What’s the usage of callback interfaces in hibernate?
Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.
Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.
21. When an instance goes in detached state in hibernate?
When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.
When an instance was earlier associated with some persistent context (e.g. a table) and is no longer associated, it’s called to be in detached state.
22. What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping
23. What’s transaction management in hibernate? How it works?
Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:
Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:
[java]
Session s = null;
Transaction tr = null;
try {
s = sessionFactory.openSession();
tr = s.beginTransaction();
doTheAction(s);
tr.commit();
} catch (RuntimeException exc) {
tr.rollback();
} finally {
s.close();
}
Session s = null;
Transaction tr = null;
try {
s = sessionFactory.openSession();
tr = s.beginTransaction();
doTheAction(s);
tr.commit();
} catch (RuntimeException exc) {
tr.rollback();
} finally {
s.close();
}
[/java]
24. What the two methods are of hibernate configuration?
We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)
We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)
25. What is the default cache service of hibernate?
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.
26. What are the two mapping associations used in hibernate?
In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association
In hibernate; we have following two types of mapping associations between entities:
a. One-to-One Association
b. Many-to-Many Association
27. What’s the usage of Hibernate QBC API?
Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.
28. In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL
Hibernate Query By Criteria (QBC) API is used to create queries by manipulation of criteria objects at runtime.
28. In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL
29. How primary key is created by using hibernate?
Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:
Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:
[xml]
<id name=”deptId” type=”string” >
<column name=”columnId” length=”30″/>
<generator/>
</id>
[/xml]
<id name=”deptId” type=”string” >
<column name=”columnId” length=”30″/>
<generator/>
</id>
[/xml]
30. How can we reattach any detached objects in Hibernate?
Objects which have been detached and are no longer associated with any persistent entities can be reattached by calling session.merge() method of session class.
31. What are different ways to disable hibernate second level cache?
31. What are different ways to disable hibernate second level cache?
Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider
a. By setting use_second_level_cache as false.
b. By using CACHEMODE.IGNORE
c. Using cache provider as org.hibernate.cache.NoCacheProvider
32. What is ORM metadata?
All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.
All the mapping between classes and tables, properties and columns, Java types and SQL types etc is defined in ORM metadata.
33. Which one is the default transaction factory in hibernate?
With hibernate 3.2, default transaction factory is JDBCTransactionFactory.
With hibernate 3.2, default transaction factory is JDBCTransactionFactory.
34. What’s the role of JMX in hibernate?
Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.
35. How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
Java Applications and components are managed in hibernate by a standard API called JMX API. JMX provides tools for development of efficient and robust distributed, web based solutions.
35. How can we bind hibernate session factory to JNDI ?
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
36. In how many ways objects can be identified in Hibernate?
Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.
Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.
37. What different fetching strategies are of hibernate?
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching
38. How mapping of java objects is done with database tables?
To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching
38. How mapping of java objects is done with database tables?
To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:
[xml]
<hibernate-mapping>
<class name=”Student” table=”tbl_student”>
<property column=”studentname” length=”255″
name=”studentName” not-null=”true” type=”java.lang.String”/>
<property column=”studentDisciplne” length=”255″
name=”studentDiscipline” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
[/xml]
<hibernate-mapping>
<class name=”Student” table=”tbl_student”>
<property column=”studentname” length=”255″
name=”studentName” not-null=”true” type=”java.lang.String”/>
<property column=”studentDisciplne” length=”255″
name=”studentDiscipline” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
[/xml]
39. What are derived properties in hibernate?
Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.
Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.
40. What is meant by a Named SQL Query in hibernate and how it’s used?
Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:
Named SQL queries are those queries which are defined in mapping file and are called as required anywhere.
For example, we can write a SQL query in our XML mapping file as follows:
[xml]
<sql-query name = “studentdetails”>
<return alias=”std”/>
SELECT std.STUDENT_ID AS {std.STUDENT_ID},
std.STUDENT_DISCIPLINE AS {std.discipline},
<return alias=”std”/>
SELECT std.STUDENT_ID AS {std.STUDENT_ID},
std.STUDENT_DISCIPLINE AS {std.discipline},
FROM Student std WHERE std.NAME LIKE :name
</sql-query>
</sql-query>
[/xml]
Then this query can be called as follows:
[java]
List students = session.getNamedQuery(&quot;studentdetails&quot;)
.setString(&quot;TomBrady&quot;, name)
.setMaxResults(50)
.list();
.setString(&quot;TomBrady&quot;, name)
.setMaxResults(50)
.list();
[/java]
41. What’s the difference between load() and get() method in hibernate?
Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.
Load() methods results in an exception if the required records isn’t found in the database while get() method returns null when records against the id isn’t found in the database.
So, ideally we should use Load() method only when we are sure about existence of records against an id.
42. What’s the use of version property in hibernate?
Version property is used in hibernate to know whether an object is in transient state or in detached state.
Version property is used in hibernate to know whether an object is in transient state or in detached state.
43. What is attribute oriented programming?
In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.
In Attribute oriented programming, a developer can add Meta data (attributes) in the java source code to add more significance in the code. For Java (hibernate), attribute oriented programming is enabled by an engine called XDoclet.
44. What’s the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn’t check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.
45. Does hibernate support polymorphism?
Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.
Yes, hibernate fully supports polymorphism. Polymorphism queries and polymorphism associations are supported in all mapping strategies of hibernate.
46. What the three inheritance models are of hibernate?
Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class
Hibernate has following three inheritance models:
a. Tables Per Concrete Class
b. Table per class hierarchy
c. Table per sub-class
47. How can we map the classes as immutable?
If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false
If we don’t want an application to update or delete objects of a class in hibernate, we can make the class as immutable by setting mutable=false
48. What’s general hibernate flow using RDBMS?
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.
49. What is Light Object Mapping?
Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.
Light Object Mapping is one of the levels of ORM quality in which all entities are represented as classes and they are mapped manually.
50. What’s difference between managed associations and hibernate associations?
Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.
Managed associations relate to container management persistence and are bi-directional while hibernate associations are unidirectional.
Read more at http://www.gointerviews.com/hibernate-interview-questions/#Dj5aBil51RBfD6lv.99
============================================================
What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections. Hibernate eliminates developers to spend more time on writing the native SQL queries and understand the complete underlying database persistence mechanism. It is a beautiful approach for persisting into database using the java objects. Having good knowledge on database is added advantage to write the more efficient hibernate programming. If you are looking to study more details on hibernate, please read the below articles:
2) What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.
3) What does an ORM solution comprises of?
- It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes
- Should have a language or an API for specifying queries that refer to the classes and the properties of classes
- An ability for specifying mapping metadata
- It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions
4) What are the different levels of ORM quality?
There are four levels defined for ORM quality.
- Pure relational
- Light object mapping
- Medium object mapping
- Full object mapping
5) What is a pure relational ORM?
The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.
6) What is a meant by light object mapping?
The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.
7) What is a meant by medium object mapping?
The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.
8)What is meant by full object mapping?
Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.
9) What are the benefits of ORM and Hibernate?
There are many benefits from these. Out of which the following are the most important one.
- Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.
- Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.
- Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.
- Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.
10) How does hibernate code looks like?
1
2
3
4
5
6
| Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); MyPersistanceClass mpc = new MyPersistanceClass ( "Sample App" ); session.save(mpc); tx.commit(); session.close(); |
The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.
11) What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
1
2
3
4
5
6
7
8
9
10
11
12
| <?xml version= "1.0" ?> <!DOCTYPE hibernate-mapping PUBLIC <hibernate-mapping> < class name= "sample.MyPersistanceClass" table= "MyPersitaceTable" > <id name= "id" column= "MyPerId" > <generator class = "increment" /> </id> <property name= "text" column= "Persistance_message" /> <many-to-one name= "nxtPer" cascade= "all" column= "NxtPerId" /> </ class > </hibernate-mapping> |
Everything should be included undertag. This is the main tag for an xml mapping document.
12) Show Hibernate overview?
13) What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important one.
- Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.
- SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.
- Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.
- Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.
- Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.
14) What are Callback interfaces?
These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.
15) What are Extension interfaces?
When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.
16) What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
- ProxyFactory interface – used to create proxies
- ConnectionProvider interface – used for JDBC connection management
- TransactionFactory interface – Used for transaction management
- Transaction interface – Used for transaction management
- TransactionManagementLookup interface – Used in transaction management.
- Cahce interface – provides caching techniques and strategies
- CacheProvider interface – same as Cache interface
- ClassPersister interface – provides ORM strategies
- IdentifierGenerator interface – used for primary key generation
- Dialect abstract class – provides SQL support
17) What are different environments to configure hibernate?
There are mainly two types of environments in which the configuration of hibernate application differs.
- Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.
- Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.
18) What is the file extension you use for hibernate mapping file?
19) What do
you create a SessionFactory?
1
2
3
4
|
Configuration cfg =
new Configuration(); cfg.addResource("myinstance/MyConfig.hbm.xml"); cfg.setProperties(
System.getProperties() ); SessionFactory
sessions = cfg.buildSessionFactory(); |
First, we need to create an
instance of Configuration and use that instance to refer to the location of the
configuration file. After configuring this instance is used to create the
SessionFactory by calling the method buildSessionFactory().
20) What is
meant by Method chaining?
Method chaining is a
programming technique that is supported by many hibernate interfaces. This is
less readable when compared to actual java code. And it is not mandatory to use
this format. Look how a SessionFactory is created when we use method chaining.
1
2
3
4
|
SessionFactory
sessions = new Configuration() .addResource("myinstance/MyConfig.hbm.xml") .setProperties(
System.getProperties() ) .buildSessionFactory(); |
21) What
does hibernate.properties file consist of?
This is a property file that
should be placed in application class path. So when the Configuration object is
created, hibernate is first initialized. At this moment the application will
automatically detect and read this hibernate.properties file.
1
2
3
4
5
6
7
8
|
hibernate.connection.datasource
= java:/comp/env/jdbc/AuctionDB
hibernate .transaction.factory_class
= net.sf.hibernate.transaction.JTATransactionFactory hibernate.transaction.manager_lookup_class
= net.sf.hibernate.transaction.JBossTransactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect |
22) What
should SessionFactory be placed so that it can be easily accessed?
As far as it is compared to
J2EE environment, if the SessionFactory is placed in JNDI then it can be easily
accessed and shared between different threads and various components that are
hibernate aware. You can set the SessionFactory to a JNDI by configuring a
property hibernate.session_factory_namein the hibernate.properties file.
23) What are
POJOs?
POJO stands for plain old java
objects. These are just basic JavaBeans that have defined setter and getter
methods for all the properties that are there in that bean. Besides they can
also have some business logic related to that property. Hibernate applications
works efficiently with POJOs rather then simple java classes.
24) What is
object/relational mapping metadata?
ORM tools require a metadata
format for the application to specify the mapping between classes and tables,
properties and columns, associations and foreign keys, Java types and SQL
types. This information is called the object/relational mapping metadata. It defines
the transformation between the different data type systems and relationship
representations.
25) What is
HQL?
HQL stands for Hibernate Query
Language. Hibernate allows the user to express queries in its own portable SQL
extension and this is called as HQL. It also allows the user to express in
native SQL.
26) What are
the different types of property and class mappings?
o
Typical and most common property mapping
1
|
<property
name="description" column="DESCRIPTION"
type="string"/> |
Or
1
2
3
|
<property name="description"
type="string"> <column
name="DESCRIPTION"/> </property> |
o
Derived properties
1
2
|
<property
name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b where
b.ITEM_ID = ITEM_ID )" type="big_decimal"/> |
o
Typical and most common property mapping
1
|
<property
name="description" column="DESCRIPTION"
type="string"/> |
o
Controlling inserts and updates
1
2
|
<property
name="name" column="NAME"
type="string" insert="false"
update="false"/> |
27) What is
Attribute Oriented Programming?
XDoclet has brought the concept
of attribute-oriented programming to Java. Until JDK 1.5, the Java language had
no support for annotations; now XDoclet uses the Javadoc tag format
(@attribute) to specify class-, field-, or method-level metadata attributes.
These attributes are used to generate hibernate mapping file automatically when
the application is built. This kind of programming that works on attributes is
called as Attribute Oriented Programming.
28) What are
the different methods of identifying an object?
There are three methods by
which an object can be identified.
1.
Object identity – Objects are identical if they reside in the
same memory location in the JVM. This can be checked by using the = = operator.
2.
Object equality – Objects are equal if they have the same value,
as defined by the equals( ) method. Classes that don’t explicitly override this
method inherit the implementation defined by java.lang.Object, which compares
object identity.
3.
Database identity – Objects stored in a relational database are
identical if they represent the same row or, equivalently, share the same table
and primary key value.
29) What are
the different approaches to represent an inheritance hierarchy?
1.
Table per concrete class.
2.
Table per class hierarchy.
3.
Table per subclass.
30) What are
managed associations and hibernate associations?
Associations that are related
to container management persistence are called managed associations. These are
bi-directional associations. Coming to hibernate associations, these are
unidirectional.
================================================================================
Q. What is a second-level
cache in Hibernate?
A. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the SessionFactory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. The second-level cache needs to be explicitly configured. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.
The Hibernate configuration looks like:
A. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the SessionFactory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. The second-level cache needs to be explicitly configured. Hibernate provides a flexible concept to exchange cache providers for the second-level cache. By default Ehcache is used as caching provider. However more sophisticated caching implementation can be used like the distributed JBoss Cache or Oracle Coherence.
The Hibernate configuration looks like:
1
2
|
<property
name="hibernate.cache.use_second_level_cache">true</property> <property
name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> |
The ehcache.xml can be configured to cache objects of type com.myapp.Order as shown below
1
2
3
4
5
6
7
8
9
10
|
<cache
name="com.myapp.Order" maxElementsInMemory="300" eternal="true" overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="300" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> |
second-level cache reduces the database traffic by caching loaded objects at the SessionFactory level between transactions. These objects are available to the whole application, not just to the user running the query. The 'second-level' cache exists as long as the session factory is alive. The second-level cache holds on to the 'data' for all properties and associations (and collections if requested) for individual entities that are marked to be cached. It is imperative to implement proper cache expiring strategies as caches are never aware of changes made to the persistent store by another application. he following are the list of possible cache strategies.
·
Read-only: This is useful for data that is read frequently, but never
updated. This is the most simplest and best-performing cache strategy.
·
Read/write: Read/write caches may be appropriate if your data needs to be
updated. This carry more overhead than read-only caches. In non-JTA
environments, each transaction should be completed when session.close() or
session.disconnect() is called.
·
Nonstrict read/write: This is most appropriate for data that is
read often but only occasionally modified.This strategy does not guarantee that
two transactions won't simultaneously modify the same data.
·
Transactional: This is a fully transactional cache that may be used only in a
JTA environment.
It can be enabled via the Hibernate mapping files as shown below:
1
2
3
4
5
|
<class
name="com.myapp.Order"> <cache
usage="read-write"/> .... </class> |
Note: The usage options are: transactional|read-write|nonstrict-read-write|read-only. The cache can also be enabled at different granular level (e.g. parent, children, etc). The active orders will be cached for 300 seconds.
-->
Q. How does the hibernate second-level cache work?
A. Hibernate always tries to first retrieve objects from the session and if this fails it tries to retrieve them from the second-level cache. If this fails again, the objects are directly loaded from the database. Hibernate's static initialize() method, which populates a proxy object, will attempt to hit the second-level cache before going to the database. The Hibernate class provides static methods for manipulation of proxies.
1
2
3
4
5
|
public final class Hibernate extends Object { .... public
static void initialize(Object proxy) throws HibernateException ....
} |
As a consequence of using the Hibernate second-level cache, you have to be aware of the fact that each call of a data access method can either result in a cache hit or miss. So, configure your log4j.xml to log your hits and misses.
1
2
3
|
<logger
name="org.hibernate.cache"> <level
value="DEBUG" /> </logger> |
Alternatively, you can use Spring AOP to log the cache access on your DAO methods.
The second level cache is a powerful mechanism for improving performance and scalability of your database driven application. Read-only caches are easy to handle, while read-write caches are more subtle in their behavior. Especially, the interaction with the Hibernate session can lead to unwanted behavior.
Q. What is a query cache in Hibernate?
A. The query cache is responsible for caching the results and to be more precise the keys of the objects returned by queries. Let us have a look how Hibernate uses the query cache to retrieve objects. In order to make use of the query cache we have to modify the person loading example as follows.
1
2
3
4
|
Query query =
session.createQuery("from Order as o where o.status=?"); query.setInt(0,
"Active"); query.setCacheable(true);
// the query is cacheable List l =
query.list(); |
You also have to change the hibernate configuration to enable the query cache. This is done by adding the following line to the Hibernate configuration.
<property name="hibernate.cache.use_query_cache">true</property>
Q. What are the pitfalls of second level and query caches?
A. Memeory is a finite resource, and over use or incorrect useage like cacheing the Order object and all its referenced objects can cause OutOfMemoryError. Here are some tips to overcome the pitfalls relating to cacheing.
1. Set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters. Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.
In the example below, the entire customer and everything he/she references would be held in cache until either the query cache exceeds its configured limits and it is evicted, or the table is modified and the results become dirty.
1
2
3
4
5
|
final Customer
customer = ... ; final String hql =
"FROM Order as order WHERE order.custOrder = ?" final Query q =
session.createQuery(hql); q.setParameter(0,
customer); q.setCacheable(true); |
Instead of setting the whole customer object as shown above, just set the id.
1
2
3
4
5
|
final Order customer
= ... ; final String hql =
"from Order as order where order.cusomer.id = ?" final Query q =
session.createQuery(hql); q.setParameter(0,
customer.getId()); q.setCacheable(true); |
2. Hibernate's query cache implementation is pluggable by decorating Hibernate's query cache implementation. This involves overriding the put( ) method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists.
3. If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.
Here are some general performance tips:
1. Session.load will always try to use the cache. Session.find does not use the cache for the primary object, but cause the cache to be populated. Session.iterate always uses the cache for the primary object and any associated objects.
2. While developing, enable the show SQL and monitor the generated SQL.
<property name="show_sql">true</property>
Also enable the "org.hibernate.cache" logger in your log4j.xml to monitor cache hits and misses.
=============================================================================
1.
What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate
communication with RDBMS is :
§
Load the Hibernate configuration file and create
configuration object. It will automatically load all hbm mapping files
§
Create session factory from configuration object
§
Get one session from this session factory
§
Create HQL Query
§
Execute query to get list containing Java objects
2.
What is Hibernate Query Language (HQL)
Hibernate offers a query
language that embodies a very powerful and flexible mechanism to query, store,
update, and retrieve objects from a database. This language, the Hibernate
query Language (HQL), is an object-oriented extension to SQL.
3.
How do you map Java Objects with Database tables?
§
First we need to write Java domain objects (beans with setter and
getter).
§
Write hbm.xml, where we map java class to table and
database columns to Java class variables.
Example :
01 |
<hibernate-mapping> |
|
02 |
03 |
<class
name="com.test.User" table="user"> |
|
04 |
05 |
<property
column="USER_NAME" length="255" |
|
06 |
07 |
name="userName"
not-null="true" type="java.lang.String"/> |
|
08 |
09 |
<property
column="USER_PASSWORD" length="255" |
|
10 |
11 |
name="userPassword"
not-null="true" type="java.lang.String"/> |
|
12 |
13 |
</class> |
|
14 |
15 |
</hibernate-mapping> |
4.
What’s 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.
|
Hibernate offers a query
language that embodies a very powerful and flexible mechanism to query, store,
update, and retrieve objects from a database. This language, the Hibernate
query Language (HQL), is an object-oriented extension to SQL.
5.
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.
6.
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>
7.
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?
8.
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”/>
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();
9.
How do you invoke Stored Procedures?
<sql-query
name=”selectAllEmployees_SP” callable=”true”>
<return alias=”emp”>
<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>
10.
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();
=============================================================================================
1.
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.
2.
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.
3.
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.
4.
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>
5.
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.
6.
What is the difference between sorted and ordered collection in hibernate?
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.
|
If your
collection is very large, it will be more efficient way to sort it .
|
7.
what are the Collection types in Hibernate ?
§
Bag
§
Set
§
List
§
Array
§
Map
8.
What is Hibernate proxy?
The proxy attribute enables
lazy initialization of persistent instances of the class. Hibernate will
initially return CGLIB proxies which implement the named interface. The actual
persistent object will be loaded when a method of the proxy is invoked.
9.
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
10.
What are the ways to express joins in HQL?
HQL provides four ways of
expressing (inner and outer) joins:-
§
An implicit association join
§
An ordinary join in the FROM clause
§
A fetch join in the FROM clause.
§
A theta-style join in the WHERE clause.
=================================================================================
1.
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. This forces hibernate to by
pass the setter method and
access the instance variable directly while initializing a newly loaded object.
2.
What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC
|
Hibernate
|
With
JDBC, developer has to write code to map an object model’s data
representation to a relational data model and its corresponding database
schema.
|
Hibernate
is flexible and powerful ORM solution to map Java classes to database tables.
Hibernate itself takes care of this mapping using XML files so developer does
not need to write code for this.
|
With
JDBC, the automatic mapping of Java objects with database tables and vice
versa conversion is to be taken care of by the developer manually with lines
of code.
|
Hibernate
provides transparent persistence and developer does not need to write code
explicitly to map database tables tuples to application objects during
interaction with RDBMS.
|
JDBC
supports only native Structured Query Language (SQL). Developer has to find
out the efficient way to access database, i.e. to select effective query from
a number of queries to perform same task.
|
Hibernate
provides a powerful query language Hibernate Query Language (independent from
type of database) that is expressed in a familiar SQL like syntax and
includes full support for polymorphic queries. Hibernate also supports native
SQL statements. It also selects an effective way to perform a database
manipulation task for an application.
|
Application
using JDBC to handle persistent data (database tables) having database
specific code in large amount. The code written to map table data to
application objects and vice versa is actually to map table fields to object
properties. As table changed or database changed then it’s essential to
change object structure as well as to change code written to map
table-to-object/object-to-table.
|
Hibernate
provides this mapping itself. The actual mapping between tables and
application objects is done in XML files. If there is change in Database or
in any table then the only need to change XML file properties.
|
With JDBC, it is developer’s responsibility to handle JDBC result set and
convert it to Java objects through code to use this persistent data in
application. So with JDBC, mapping between Java objects and database tables
is done manually.
|
Hibernate,
with Transparent Persistence, cache is set to application work space.
Relational tuples are moved to this cache as a result of query. It improves
performance if client application reads same data many times for same write.
Automatic Transparent Persistence allows the developer to concentrate more on
business logic rather than this application code.
|
In JDBC there
is no check that always every user has updated data. This check has to be
added by the developer.
|
Hibernate
enables developer to define version type field to application, due to this
defined field Hibernate updates version field of database table every time
relational tuple is updated in form of Java class object to that table. So if
two users retrieve same tuple and then modify it and one user save this
modified tuple to database, version is automatically
|
3.
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.
4.
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.
•
dynamic-update (defaults to false): Specifies that UPDATE SQL should be
generated at runtime and contain only those columns whose values have changed.
•
dynamic-insert (defaults to false):Specifies that INSERT SQL should be
generated at runtime and contain only the columns whose values are not null.
5.
What do you mean by fetching strategy ?
fetching strategy is the
strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association. Fetch strategies may be declared
in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria
query.
6.
What is automatic dirty checking?
Automatic dirty checking is a
feature that saves us the effort of explicitly asking Hibernate to update the
database when we modify the state of an object inside a transaction.
7.
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.
8.
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.
9.
What are the types of Hibernate instance states ?
Three types of instance states:
•
Transient -The instance is not associated with any persistence context
•
Persistent -The instance is associated with a persistence context
•
Detached -The instance was associated with a persistence context which has been
closed – currently not associated
10.
What are the differences between EJB 3.0 & Hibernate?
Hibernate Vs EJB 3.0 :-
Hibernate
|
EJB 3.0
|
Session-
Cache or collection of loaded objects relating to a single unit of work
|
Persistence
Context-Set of entities that can be managed by a given EntityManager is
defined by a persistence unit
|
XDoclet
Annotations used to support Attribute Oriented Programming
|
Java 5.0
Annotations used to support Attribute Oriented Programming
|
Defines
HQL for expressing queries to the database
|
Defines
EJB QL for expressing queries
|
Supports
Entity Relationships through mapping files and annotations in JavaDoc
|
Support
Entity Relationships through Java 5.0 annotations
|
Provides
a Persistence Manager API exposed via the Session, Query, Criteria, and
Transaction API
|
Provides
and Entity Manager Interface for managing CRUD operations for an Entity
|
Provides callback support through lifecycle, interceptor,
and validatable interfaces
|
Provides
callback support through Entity Listener and Callback methods
|
Entity
Relationships are unidirectional. Bidirectional relationships are implemented
by two unidirectional relationships
|
Entity
Relationships are bidirectional or unidirectional
|
============================================================================================
1.
What is ORM?
ORM stands for
object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database
2.
What does ORM consists of?
An ORM solution consists of the
following four pieces:
API for performing basic CRUD
operations
API to express queries refering
to classes
Facilities to specify metadata
Optimization facilities :
Dirty checking,lazy
associations fetching
3.
Why do you need ORM tools like hibernate?
The main advantage of ORM like
hibernate is that it shields developers from messy SQL. Apart from this,
ORM provides following
benefits:
Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
Improved performance
Sophisticated caching Lazy
loading Eager loading Improved maintainability
A lot less code to write
Improved portability
ORM framework generates
database-specific SQL for you
4.
What does Hibernate simplify?
Hibernate simplifies: Saving
and retrieving your domain objects Making database column and table name
changes Centralizing pre save and post retrieve logic Complex joins for
retrieving related items Schema creation from object model
5.
What is the need for hibernate xml mapping file?
Hibernate mapping file tells
Hibernate which tables and columns to use to load and store objects. Typical
mapping file look as follows:
6.
What are the most common methods of hibernate configuration?
The most common methods of
Hibernate configuration are:
Programmatic configuration XML
configuration (hibernate.cfg.xml)
7.
What are the important tags of hibernate .cfg.xml?
Following are the important
tags of hibernate.cfg.xml:
8.
What are the Core interface are of hibernate framework?
The five core interfaces are
used in just about every Hibernate application. Using these interfaces, you can
store and retrieve persistent objects and control transactions. Session
interface SessionFactory interface Configuration interface Transaction
interface Query and Criteria interfaces
9.
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: Wraps a
JDBC connection Factory for Transaction Holds a mandatory (first-level) cache
of persistent objects, used when navigating the object graph or looking up
objects by identifier.
10.
What role does the session Factory 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
SessionFactory sessionFactory =
configuration.buildSessionFactory();
============================================================================================
1.
What is a Session Factory? Is it a thread-safe object?
SessionFactory is Hibernates
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.
SessionFactory sessionFactory =
new Configuration().configure().buildSessionfactory();
2.
What is a Session? Can you share a session object between different thread?
Session is a light weight and a
non-threadsafe object (No, you cannot share it between threads) that represents
a single unit-of-work with the database. Sessions are opened by a
SessionFactory and then are closed when all work is complete. Session is the
primary interface for the persistence service. A session obtains a database
connection lazily (i.e. only when required). To avoid creating too many sessions
ThreadLocal class can be used as shown below to get the current session no
matter how many times you make call to the currentSession() method.
01 |
& |
|
02 |
03 |
public class HibernateUtil { |
|
04 |
05 |
& |
|
06 |
07 |
public static final ThreadLocal local = new ThreadLocal(); |
|
08 |
09 |
|
|
10 |
11 |
public static Session currentSession() throws HibernateException { |
|
12 |
13 |
Session session =
(Session) local.get(); |
|
14 |
15 |
//open a new session
if this thread has no session |
|
16 |
17 |
if(session
== null) { |
|
18 |
19 |
session =
sessionFactory.openSession(); |
|
20 |
21 |
local.set(session); |
|
22 |
23 |
} |
|
24 |
25 |
return session; |
|
26 |
27 |
} |
|
28 |
29 |
} |
It is also vital that you close
your session after your unit of work completes. Note: Keep your Hibernate
Session API handy.
3.
What are the benefits of detached objects?
Detached objects can be passed
across layers all the way up to the presentation layer without having to use
any DTOs (Data Transfer Objects). You can later on re-attach the detached
objects to another session.
4.
How does Hibernate distinguish between transient(i.e. newly instantiated ) and
detached object?
” Hibernate uses the
versionproperty, if there is one.
” If not uses the identifier
value. No identifier value means a new object. This does work only for
Hibernate managed surrogate keys. Does not work for natural keys and assigned
(i.e. not managed by Hibernate) surrogate keys.
” Write your own strategy with
Interceptor.isUnsaved().
5.
What are the pros and cons of detached objects?
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 better to not 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.
6.
What are the general considerations or best practices for defining your
Hibernate persistent classes?
§
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.
§
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.
§
It is recommended to
implement the Serializable interface. This is potentially useful if you want to
migrate around a multi-processor cluster.
§
The persistent class
should not be final because if it is final then lazy loading cannot be used by
creating proxy objects.
§
Use XDoclet tags for
generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are
less verbose than *.hbm.xml files.
7.
Explain about the transparent presistence of Hibernate?
Transparent persistence is
provided for Plain old Java objects or POJOs. For proper functioning of
theapplications importance should be given to the methods equals () and hash
Code methods (). It has a requirement which should be strictly followed in the
applications which is a no-argument constructor.
8.
Explain about the Primary feature of Hibernate?
Primary feature of hibernate is
to java classes to database tables. Data query and retrieval is also possible
with Hibernate. Application portability is a key feature in Hibernate it allows
developers to port applicationsto almost all SQL databases
9.
Explain about transaction file?
Transactions denote a work file
which can save changes made or revert back the changes.A transaction can be
started by session.beginTransaction() and it uses JDBC connection, CORBA or
JTA. When this session starts several transactions may occur.
10.
What is the effect when a transient mapped object is passed onto a sessions
save?
When a Sessions save () is
passed to a transient mapped object it makes the method to become more
persistent. Garbage collection and termination of the Java virtual machine
stays as long as it is deleted explicitly. It may head back to its transient
state.
========================================================================1.
Explain about version field?
Application
level data integrity constants are important if you are making changes to
offline information which is again backed by database. Higher level locking or
versioning protocol is required to support them. Version field usage comes at
this stage but the design and implementation process is left to the developer.
2.
Explain about addClass function?
This
function translates a Java class name into file name. This translated file name
is then loaded as an input stream from the Java class loader. This addclass
function is important if you want efficient usage of classes in your code.
3.
Expalin about addjar() and adddirectory() methods?
These
methods are the most convenient to use in hibernate. These methods allow you to
load all your Hibernate documents at a time. These methods simplify code
configuration, refactoring, layout, etc. These functions help you to add your
hibernate mapping to Hibernate initialization files.
4.
Explain about the id field?
The id
field corresponds to the surrogate key which is generated by the database.
These fields are handled by the id field. Name attribute is used to specify the
names of the field and it should correspond to the method name of getid. This
also should correspond to long type and the values should be stored I the
database in the long column.
5.
What is lazy initialization in hibernate?
Lazy
setting decides whether to load child objects while loading the Parent Object.
You need to specify parent class.Lazy = true in hibernate mapping file. By
default the lazy loading of the child objects is true. This make sure that the
child objects are not loaded unless they are explicitly invoked in the
application by calling getChild() method on parent. In this case hibernate
issues a fresh database call to load the child when getChild() is actually
called on the Parent object. But in some cases you do need to load the child
objects when parent is loaded. Just make the lazy=false and hibernate will load
the child when parent is loaded from the database. Examples: Address child of
User class can be made lazy if it is not required frequently. But you may need
to load the Author object for Book parent whenever you deal with the book for
online bookshop.
Hibernate
does not support lazy initialization for detached objects. Access to a lazy
association outside of the context of an open Hibernate session will result in
an exception.
6.
What is DAO ?
The Java
Data Access Object (Java DAO) is an important component in business
applications. Business applications almost always need access to data from
relational or object databases and the Java platform offers many techniques for
accessingthis data. The oldest and most mature technique is to use the Java
Database Connectivity (JDBC)API, which provides the capability to execute SQL
queries against a databaseand then fetch the results, one column at a time.
Although this API provideseverything a developer needs to access data and to
persist application state,it is a cumbersome API to develop against – which
makes a Java DAO code generator particularly useful.
7.
Explain the important feature of DAO ?
The Data
Access Object design pattern provides a technique for separating object
persistence and data access logic from any particular persistencemechanism or
API. There are clear benefits to this approach from anarchitectural
perspective. The Java DAO approach provides flexibility to change
anapplication’s persistence mechanism over time without the need to
re-engineerapplication logic that interacts with the Data Access Object tier.
For example, there may beperformance benefits in changing an application’s
performance mechanism fromusing Entity Beans to using direct JDBC calls from a
session bean, or even amove to an alternative persistence framework, such as
Hibernate. Without a Java DAO tierin place, this sort of transition would
require extensive re-engineering ofexisting code.
8.
What is connection pooling?
Connection
pooling is a technique of creating and managing a pool of connections that are
ready for use by any thread that needs them.
This
technique of pooling connections is based on the fact that most applications
only need a thread to have access to a JDBC connection when they are actively
processing a transaction, which usually take only milliseconds to complete.
When not processing a transaction, the connection would otherwise sit idle.
Instead, connection pooling allows the idle connection to be used by some other
thread to do useful work.
In
practice, when a thread needs to do work against a MySQL or other database with
JDBC, it requests a connection from the pool. When the thread is finished using
the connection, it returns it to the pool, so that it may be used by any other
threads that want to use it.
When the
connection is loaned out from the pool, it is used exclusively by the thread
that requested it. From a programming point of view, it is the same as if your
thread called DriverManager.getConnection() every time it needed a JDBC
connection, however with connection pooling, your thread may end up using
either a new, or already-existing connection.
9.
What is the necessity of connection polling?
Benefits of
Connection Pooling:
Connection
pooling can greatly increase the performance of your Java application, while
reducing overall resource usage. The main benefits to connection pooling are:
Reduced
connection creation time:
While this
is not usually an issue with the quick connection setup that MySQL offers
compared to other databases, creating connections still has networking and JDBC
driver overhead that will be avoided if connections are recycled.
Simplified programming
model:
When using
connection pooling, each individual thread can act as though it has created its
own JDBC connection, allowing you to use straight-forward JDBC programming
techniques.
Controlled
resource usage:
If you
don’t use connection pooling, and instead create a new connection every time a
thread needs one, your application’s resource usage can be quite wasteful and
lead to unpredictable behavior under load.
Remember
that each connection to MySQL has overhead (memory, CPU, context switches, etc)
on both the client and server side. Every connection limits how many resources
there are available to your application as well as the MySQL server. Many of
these resources will be used whether or not the connection is actually doing
any useful work!
Connection
pools can be tuned to maximize performance, while keeping resource utilization
below the point where your application will start to fail rather than just run
slower.
10.
What is QBECK (que) QC(qbc)?
========================================================================================
What is the purpose of dialect?
There are
two concepts here a Dialect and a Driver.
Driver is
like English.
Dialect is
the different pronunciations of English.
We all know
there are different versions of Oracle… Oracle 9i, Oracle8.
The driver
we would use would be a common for all of these.
But the
dialect we use is specific to each one of them, which helps Hibernate in
generating optimized queries to those specific versions of database.
Also not
that this is not mandatory to be given in cfg.xml.
This is the
SQL dialect (database type) for the database being used. Any valid Hibernate
dialect may be used. A few the more commonly used dialects are:
§
net.sf.hibernate.dialect.HSQLDialect
§
net.sf.hibernate.dialect.Oracle9Dialect
§
net.sf.hibernate.dialect.MySQLDialect
§
net.sf.hibernate.dialect.SQLServerDialect
§
net.sf.hibernate.dialect.FirebirdDialect
2.
How to create the table dynamically in hibernate?
I have
managed to setup an application that inserts, retrives, and delete objects in a
database. I have also instructed hibernate to update the set of tables when
ever it restarts (with hibernate.hbm2ddl.auto=update)
3.
What is native SQL ?
They are
loosely integrated into ABAP. It allows access to all functions containing
programming interface. They are not checked and converted. They are sent
directly to the database system. Programs that use Native SQL are specific to
the database system for which they were written. For e.g. to create or change
table definition in the ABAP.
4.
What are the different types of mapping?
Hibernate
built-in mapping types usually share the name of the Java type they map;
however, there may be more than one Hibernate mapping type for a partucular
Java type. The various built-in-mapping types available in Hibernate are:
§
Java primitive mapping types
§
Date and time mapping types
§
Large object mapping types
§
Various JDK mapping types
5.
What is ACID properties?
The
ACID properties are:
§
Atomicity
§
Consistency
§
Isolation
§
Durability
Atomicity –
A transaction must be an atomic unit of work; either all of its data
modifications are performed or none of them is performed.
Consistency
– When completed, a transaction must leave all data in a consistent state. In a
relational database, all rules must be applied to the transaction’s
modifications to maintain all data integrity. All internal data structures,
such as B-tree indexes or doubly-linked lists, must be correct at the end of
the transaction.
Isolation –
Modifications made by concurrent transactions must be isolated from the
modifications made by any other concurrent transactions. A transaction either
sees data in the state it was in before another concurrent transaction modified
it, or it sees the data after the second transaction has completed, but it does
not see an intermediate state. This is referred to as serializability because
it results in the ability to reload the starting data and replay a series of
transactions to end up with the data in the same state it was in after the
original transactions were performed.
Durability
– After a transaction has completed, its effects are permanently in place in
the system. The modifications persist even in the event of a system failure.
6.
What is transaction?
A
transaction is a set of rows bound by a commit or rollback of rows. The
transaction control transformation is used to commit or rollback a group of
rows.
7.
Types of transaction:
Long run
transaction
Short run
transaction
8.
What is isolation levels?
The following
are the transaction levels or built-in variables:
§
TC_CONTINUE_TRANSACTION:
The Integration Service does not perform any transaction change for this row.
This is the default value of the expression.
§
TC_COMMIT_BEFORE: The Integration
Service commits the transaction, begins a new transaction, and writes the
current row to the target. The current row is in the new transaction.
§
TC_COMMIT_AFTER: The Integration
Service writes the current row to the target, commits the transaction, and
begins a new transaction. The current row is in the committed transaction.
§
TC_ROLLBACK_BEFORE: The
Integration Service rolls back the current transaction, begins a new
transaction, and writes the current row to the target. The current row is in
the new transaction.
§
TC_ROLLBACK_AFTER: The
Integration Service writes the current row to the target, rolls back the
transaction, and begins a new transaction. The current row is in the rolled
back transaction.
9.
What is lock mode?
setLockMode
is a method of Hibernate Criteria API. You can use a lock mode in the following
way
1 |
Criteria criteria =
session.createCriteria(Student.class); |
|
2 |
3 |
criteria.add(Restrictions.eq("name", "Ramesh")); |
|
4 |
5 |
criteria.setLockMode("this",
LockMode.UPGRADE); |
|
6 |
7 |
List list = criteria.list(); |
10.
Difference between session.load and session.lock
The load()
method is older; get() was added to Hibernate’s API due to user request. The
difference is trivial:
The
following Hibernate code snippet retrieves a User object from the database:
User user =
(User) session.get(User.class, userID);
The get()
method is special because the identifier uniquely identifies a single instance
of a class. Hence it’s common for applications to use the identifier as a
convenient handle to a persistent object. Retrieval by identifier can use the
cache when retrieving an object, avoiding a database hit if the object is
already cached.
Hibernate
also provides a load() method:
User user =
(User) session.load(User.class, userID);
If load()
can’t find the object in the cache or database, an exception is thrown. The
load() method never returns null. The get() method returns
null if the
object can’t be found. The load() method may return a proxy instead of a real
persistent instance. A proxy is a placeholder instance of a runtime-generated
subclass (through cglib or Javassist) of a mapped persistent class, it can
initialize itself if any method is called that is not the mapped database
identifier getter-method. On the other hand, get() never returns a proxy.
Choosing between get() and load() is easy: If you’re certain the persistent
object exists, and nonexistence would be considered exceptional, load() is a
good option. If you aren’t certain there is a persistent instance with the
given identifier, use get() and test the return value to see if it’s null.
Using load() has a further implication: The application may retrieve a valid
reference (a proxy) to a persistent instance without hitting the database to
retrieve its persistent state. So load() might not throw an exception when it
doesn’t find the persistent object in the cache or database; the exception
would be thrown later, when the proxy is accessed.
OR
Hibernate
Interview Questions and Answers will guide us now that Hibernate is an
object-relational mapping (ORM) library for the Java language, providing a
framework for mapping an object-oriented domain model to a traditional
relational database. Hibernate solves object-relational impedance mismatch
problems by replacing direct persistence-related database accesses with
high_level object handling functions. Learn more about Hibernate bu this
Hibernate Interview Questions with Answers guide Select More Questions to
explore you knowledge regarding Hibernate Job Interview Questions and answers.
Explore more thousands of professional Hibernate job interview questions and
answers with us
===
1.
Types of locks
§
Read lock
§
Write lock
§
Execute lock
§
Fetch lock
§
Save lock
2.
What is 2-phase lock ?
§
Read only
transaction
§
Update transaction
3.
What are the design patterens used in hibernate?
§
Composite design
§
DAO Design Pattern
§
Abstract FactoryMVC
§
Data Transfer
§
Proxy
§
facade
4.
Whether POJO is java bean or not ?
S . POJO is
java bean…
POJO stands
for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean.
Besides they can also have some business logic related to that property.
Hibernate applications works efficiently with POJOs rather then simple java
classes.
5.
Please draw object life cycle in hibernate?
Transient
objects do not (yet) have any association with the database. they act like any
normal Java object and are not saved to the database. When the last reference
to a transient object is lost, the object itself is lost and is (eventually)
garbage collected. There is no connection between transactions and such
objects: commits and rollbacks have no effects on them. They can be turned into
persistent objects via one of thesave method calls if the Session object or by
adding a reference from a persistent object to this object.
Persistent
objects do have an association with the database. They are always associated
with a persistence manager, i.e., a Session object and they always participate
in a transaction. Actual updates of a database from the persistent object may
occur at any time between when the object is updated to the end of the
transaction: it does not necessarily happen immediately. However, this feature,
which allows important optimizations in database interactions, is essentially
invisible to the programmer. For example, one place where one might expect to
notice the difference between the in-memory persistent object and the database
version is at the point of executing a query. In such a case, Hibernate will,
if necessary, synchronise any dirty objects with the database (i.e., save them)
in order to ensure that the query returns the correct results.
A
persistent object has a primary key value set, whether or not it has been
actually saved to the database yet.
Calling the
delete method of the Session object on a persistent object will cause its
removal from the database and will make it transient.
Detached
objects are objects that were persistent but no longer have a connection to a
Session object (usually because you have closed the session). Such an object
contains data that was synchronised with the database at the time that the
session was closed, but, since then, the database may have changed; with the
result that this object is now stale.
6.
How transaction management is done in hibernate?
Transaction
simply means a unit of work, which is atomic. If only one step fails, then the
whole unit of work fails. When we consider database, Transaction groups a
set of statements/commands which gets committed together. If a single statement
fails, whole work will be rolled back. Transactions can be
described using ACID criteria.
ACID means:
A:
Atomicity: In a Transaction If only one step fails, the whole unit of
work must fail.This is known as atomicity
C :
Consistency : The Transactions operate on Consistent data. I.e. This data is
hidden from other concurrently running transactions. The data is clean and
consistent.
I:
Isolation: It means when a transaction is being executed, it will not be
visible to other concurrently running transactions. This means, any changes
done to the existing data during a transaction, before transaction finishes, is
not visible to other active transactions. They work on consistent data.
D: Durable:
Also the changes done in a transaction are durable. Even if server / system
fails after a transaction, the changes done by a successful transaction are
permanent / persistent.
So a
database transactions involve a set of SQL statements, which either
succeeds or fails. If any one of the statement fails in between, the
execution of subsequent statements are aborted and all changes done by the
previous SQL statements will be rolled back. In complex applications,
which involve different database actions, one should set boundries for a
transaction. This means beginning and end of the transaction should be decided.
This is called Transaction demarcation. If an error occurs (either while
executing operations or when committing the transaction), you have to roll back
the transaction to leave the data in a consistent state.
This can be
done in 2 ways.
In a
programmatic manner by explicitly setting boundaries in code or using JTA
API.
Setting
Transaction boundaries by declarative manner, specifying transaction boundaries
to managed containers like EJB container
7.
difference between association and component mapping?
Association
mapping refers to a many-to-one or one-to-one relationship which will be mapped
by using another class which you have mapped in Hibernate (also called an
“entity”). The associated object has its own lifecycle and is simply related to
the first object.
Component
mapping refers to mapping a class (or collection of classes) whose lifecycle is
bound tightly to the parent. This is also called “composition” in the strict
definition of the word in object-oriented programming. Basically if you delete
the parent object the child object should also be deleted; it also cannot exist
on its own without a parent.
8.
Why hibernate is called as lazy invocation ?
Lazy
setting decides whether to load child objects while loading the Parent Object.
You need to specify parent class.Lazy = true in hibernate mapping file. By
default the lazy loading of the child objects is true. This make sure that the
child objects are not loaded unless they are explicitly invoked in the application
by calling getChild() method on parent. In this case hibernate issues a fresh
database call to load the child when getChild() is actually called on the
Parent object. But in some cases you do need to load the child objects when
parent is loaded. Just make the lazy=false and hibernate will load the child
when parent is loaded from the database. Examples: Address child of User class
can be made lazy if it is not required frequently. But you may need to load the
Author object for Book parent whenever you deal with the book for online
bookshop.
Hibernate
does not support lazy initialization for detached objects. Access to a lazy
association outside of the context of an open Hibernate session will result in
an exception.
9.
What is hibernate tuning?
The key to
obtain better performance in any hibernate application is to employ SQL
Optimization, session management, and Data caching
10.
Define hibernate statistics ?
We’ve been
doing a lot of Hibernate work at Terracotta recently and that naturally
includes a fair amount of performance testing. In Hibernate, you can grab those
stats using the Statistics object for aSessionFactory via getStatistics().
There are all sorts of tasty morsels inside this class to get factory-wide
counts and per-entity/query/cache/etc stats. Cool stuff.
We noticed
however while doing some perf testing that the code inside the StatisticsImpl
is a bit problematic from a concurrency point of view. The basic gist of the
class is just a set of stat counters. I can simplify the pattern to this
without much loss of detail:
01 |
public class StatisticsImpl implements Statistics, StatisticsImplementor { |
|
02 |
03 |
private long queryExecutionCount; |
|
04 |
05 |
public synchronized void queryExecuted(String hql, int rows, long time) { |
|
06 |
07 |
queryExecutionCount++; |
|
08 |
09 |
// ... bunch of other
stat collection |
|
10 |
11 |
} |
|
12 |
13 |
public long getQueryExecutionCount() { |
|
14 |
15 |
return queryExecutionCount; |
|
16 |
17 |
} |
|
18 |
19 |
public synchronized void clear() { |
|
20 |
21 |
queryExecutionCount
= 0; |
|
22 |
23 |
// ... clear all
other stats |
|
24 |
25 |
} |
|
26 |
27 |
} |
That’s
basically what’s in this class but it’s repeated a couple dozen times for other
counters and there are Maps used for per-item counts of a few kinds of items.
There are several problems here from a concurrency point of view:
§
Coarse-grained lock – the entire
class shares a single lock via synchronized methods. That means that every
counter in every thread is contending for that same lock. The impact of this is
that when you turn on statistics collection in Hibernate, you immediately
introduce a big old stop-the-world contention point across all threads. This
will have an impact (possibly a very significant one) on the very stats you are
trying to collect. It€™s entirely possible that the scale of your application
or other bottlenecks mean that your application is not actually seeing this as
a bottleneck, but it should scare you at least a little.
At the very
least here, we could be used fine-grained locking to avoid creating contention
between different kinds of statistics. There are also collections in here that
collect stats on a per-query, per-entity, per-collection, etc basis. Those
could actually have fine-grained locks per-entity as well (but they don€™t).
§
Dirty reads -you’ll notice
that while writes to the counters are synchronized, the reads are not.
Presumably this was done for performance. Unfortunately, it’s also quite broken
from a memory model point of view. These reads are not guaranteed to see writes
from any other thread, so the values you’re seeing are possibly stale. In fact,
it’s possible that you are never seeing any of the counter updates. In
practice, the synchronization on puts is probably causing the local caches to
get flushed and on the hardware we’re running, you do seem to see values that
are in the ballpark at least. But the Java memory model makes no guarantee that
this will work on all architectures or at any point in the future.
§
Race condition on clear()
-the common way that the stats are used is with some gui or other monitor
sitting in a loop and periodically reading some (or all) of the stats, then
calling clear(). Because time passes between the read of the first stat and the
clear, you will lose all updates to the stats during the course of the
reads.You may be willing to neglect a few lost updates, but consider that in
many cases the monitor thread may iterate through every entity, collection, and
query updated since the last loop (potentially hundreds of reads). In the cases
where per-item stats are looked up, the gets() are actually synchronized as
well when finding the stat in a Map. Those gets are synchronized against all
other puts happening in the system. So the scope of that “read all stats” part
of the monitor code may actually be quite large and you will lose all updates
made between the beginning of that and the clear(), which distorts the next set
of stats to an unknown degree (more activity == more distortion).
§
[UPDATE] Dirty long read
-As Peter mentioned in the comments, the values being read here are longs and
since longs and doubles are 64-bit values, dirty reads of them are not
guaranteed to see atomic writes from other threads. So you could see different
32-bit chunks that were not written together. Reads/writes of shared doubles
and longs should always be done with synchronized or volatile to address this
issue.
I certainly
understand that stats are seen as best-effort and that the existing Hibernate
code supports pre-1.5 Java and does not have access to Java 5 concurrency
utilities like Atomic classes and concurrent collections, but even so I think
there are things that could be done here to make stats collection a lot more
accurate and less invasive. Things like fine-grained or more concurrent locking
(with volatile, AtomicInteger, or ReentrantReadWriteLock) would go a long way
towards fixing visibility while increasing concurrency.
In our
Terracotta integration, I suspect we will be using some byte-code
instrumentation to clean up these classes (we already assume Java 1.5+ so that
is a constraint that we are happy to break). As it is, we don’t currently trust
the stats in the first place and second we are actually seeing the single lock
showing up as a hot spot in performance tests.
I hope that
the next version of Hibernate (which I think is dropping pre-1.5 support?) can
make some improvements as well.
=========================================================================================
1.
what is caching?
Anything
you can do to minimize traffic between a database and an application server is
probably a good thing. In theory, an application ought to be able to maintain a
cache containing data already loaded from the database, and only hit the
database when information has to be updated. When the database is hit, the
changes may invalidate the cache
2.
Types of caching ?
§
First-Level Cache
§
Second-Level Cache
3.
What are the different options for hibernate second level of caching
Second-level
cache always associates with the Session Factory object. While running the
transactions, in between it loads the objects at the Session Factory level, so
that those objects will available to the entireapplication, don’t bounds to
single user. Since the objects are already loaded in the cache, whenever an
object is returned by the query, at that time no need to go for a database
transaction. In this way the second level cache works. Here we can use query
level cache also. Later we will discuss about it.
To activate
second-level caching, you need to define the hibernate.cache.provider_class
property in the hibernate.cfg.xml file as follows:
<
hibernate-configuration >
<
session-factory >
<
property name=”hibernate.cache.provider_class”
>org.hibernate.cache.EHCacheProvider< / property>
< / session-factory
>
< /
hibernate-configuration >
By default,
the second-level cache is activated and uses the EHCache provider.
To use the
query cache you must first enable it by setting the property
hibernate.cache.use_query_cache to true in hibernate.properties.
4.
Explain the process nof achieving second level caching
Second-level
cache always associates with the Session Factory object. While running the
transactions, in between it loads the objects at the Session Factory level, so
that those objects will available to the entire application, don’t bounds to
single user. Since the objects are already loaded in the cache, whenever an
object is returned by the query, at that time no need to go for a database
transaction. In this way the second level cache works. Here we can use query
level cache also. Later we will discuss about it.
5.
What is evict and close?
Hibernate
does a neat trick where it tracks objects that have been changes since being
loaded from the database. Once Hibernate provides an object, make a
modification and flush the Session – Hibernate knows the object was changed
and will propagate to the database accordingly.
6.
what are managed associations and hibernate associations
Associations
that are related to container management persistence are called managed
associations. These are bi-directional associations. Coming to hibernate
associations, these are unidirectional
7.
What are the different approaches to represent an inheritance hierarchy?
§
Table per concrete class.
§
Table per class hierarchy.
§
Table per subclass.
8.
What are the different methods of identifying an object?
There are
three methods by which an object can be identified.
§
Object identity – Objects are
identical if they reside in the same memory location in the JVM. This can be
checked by using the = = operator.
§
Object equality – Objects are
equal if they have the same value, as defined by the equals( ) method. Classes
that don’t explicitly override this method inherit the implementation defined
by java.lang.Object, which compares object identity.
§
Database identity – Objects
stored in a relational database are identical if they represent the same row
or, equivalently, share the same table and primary key value.
9.
What is Attribute Oriented Programming?
XDoclet has
brought the concept of attribute-oriented programming to Java. Until JDK 1.5,
the Java language had no support for annotations; now XDoclet uses the Javadoc
tag format (@attribute) to specify class-, field-, or method-level metadata
attributes. These attributes are used to generate hibernate mapping file
automatically when the application is built. This kind of programming that
works on attributes is called as Attribute Oriented Programming.
10.
What are the different types of property and class mappings?
§
Typical and most common property
mapping
<property
name=”description” column=”DESCRIPTION” type=”string”/>
Or
<property
name=”description” type=”string”>
<column
name=”DESCRIPTION”/>
</property>
§
Derived properties
<property
name=”averageBidAmount” formula=”( select AVG(b.AMOUNT) from BID b where
b.ITEM_ID = ITEM_ID )” type=”big_decimal”/>
§
Typical and most common property
mapping
<property
name=”description” column=”DESCRIPTION” type=”string”/>
§
Controlling inserts and updates
<property
name=”name” column=”NAME” type=”string” insert=”false” update=”false”/>
=================================================================
1.
What is HQL?
HQL stands
for Hibernate Query Language. Hibernate allows the user to express queries in
its own portable SQL extension and this is called as HQL. It also allows the
user to express in native SQL.
2.
What is object/relational mapping metadata?
ORM tools
require a metadata format for the application to specify the mapping between
classes and tables, properties and columns, associations and foreign keys, Java
types and SQL types. This information is called the object/relational mapping
metadata. It defines the transformation between the different data type systems
and relationship representations.
3.
What are POJOs?
POJO stands
for plain old java objects. These are just basic JavaBeans that have defined
setter and getter methods for all the properties that are there in that bean.
Besides they can also have some business logic related to that
4.
What should SessionFactory be placed so that it can be easily accessed?
As far as
it is compared to J2EE environment, if the SessionFactory is placed in JNDI
then it can be easily accessed and shared between different threads and various
components that are hibernate aware. You can set the SessionFactory to a JNDI
by configuring a property hibernate.session_factory_name in the
hibernate.properties file.
5.
What does hibernate.properties file consist of?
This is a
property file that should be placed in application class path. So when the
Configuration object is created, hibernate is first initialized. At this moment
the application will automatically detect and read this hibernate.properties
file.
§
hibernate.connection.datasource =
java:/comp/env/jdbc/AuctionDB
§
hibernate.transaction.factory_class
=net.sf.hibernate.transaction.JTATransactionFactory
§
hibernate.transaction.manager_lookup_class
= net.sf.hibernate.transaction.JBossTransactionManagerLookup
§
hibernate.dialect =
net.sf.hibernate.dialect.PostgreSQLDialect
6.
What is meant by Method chaining?
Method
chaining is a programming technique that is supported by many hibernate
interfaces. This is less readable when compared to actual java code. And it is
not mandatory to use this format. Look how a SessionFactory is created when we
use method chaining.
§
SessionFactory sessions = new
Configuration()
§
.addResource(“myinstance/MyConfig.hbm.xml”)
§
.setProperties(
System.getProperties() )
§
.buildSessionFactory();
7.
What do you create a SessionFactory?
§
Configuration cfg = new
Configuration();
§
cfg.addResource(“myinstance/MyConfig.hbm.xml”);
§
cfg.setProperties(
System.getProperties() );
§
SessionFactory sessions =
cfg.buildSessionFactory();
8.
What is the file extension you use for hibernate mapping file?
The name of
the file should be like this : filenam.hbm.xml
The
filename varies here. The extension of these files should be”.hbm.xml”.
This is
just a convention and it’s not mandatory. But this is the best practice to
follow this extension.
9.
What are different environments to configure hibernate?
There are
mainly two types of environments in which the configuration of hibernate
application differs.
§
Managed environment -In this kind
of environment everything from database connections, transaction boundaries,
security levels and all are defined. An example of this kind of environment is
environment provided by application servers such as JBoss, Weblogic and WebSphere.
§
Non-managed environment -This
kind of environment provides a basic configuration template. Tomcat is one of
the best examples that provide this kind of environment.
10.
What are the Extension interfaces that are there in hibernate?
There are
many extension interfaces provided by hibernate.
§
ProxyFactory interface – used to
create proxies
§
ConnectionProvider interface
-used for JDBC connection management
§
TransactionFactory interface –
Used for transaction management
§
Transaction interface -Used for
transaction management
§
TransactionManagementLookup
interface- Used in transaction management.
§
Cahce interface -provides caching
techniques and strategies
§
CacheProvider interface -same as
Cache interface
§
ClassPersister interface –
provides ORM strategies
§
IdentifierGenerator interface –
used for primary key generation
§
Dialect abstract class – provides
SQL support
§
===================================================================
1.
What are Extension interfaces?
When the
built-in functionalities provided by hibernate is not sufficient enough, it
provides a way so that user can include other interfaces and implement those
interfaces for user desire functionality. These interfaces are called as
Extension interfaces.
2.
What are Callback interfaces?
These
interfaces are used in the application to receive a notification when some
object events occur. Like when an object is loaded, saved or deleted. There is
no need to implement callbacks in hibernate applications, but they’re useful
for implementing certain kinds of generic functionality.
3.
What the Core interfaces are of hibernate framework?
There are
many benefits from these. Out of which the following are the most important
one.
§
Session Interface -This is the
primary interface used by hibernate applications. The instances of this
interface are lightweight and are inexpensive to create and destroy. Hibernate
sessions are not thread safe.
§
SessionFactory Interface -This is
a factory that delivers the session objects to hibernate application. Generally
there will be a single SessionFactory for the whole application and it will be
shared among all the application threads.
§
Configuration Interface -This
interface is used to configure and bootstrap hibernate. The instance of this
interface is used by the application in order to specify the location of
hibernate specific mapping documents.
§
Transaction Interface -This is an
optional interface but the above three interfaces are mandatory in each and
every application. This interface abstracts the code from any kind of
transaction implementations such as JDBC transaction, JTA transaction.
§
Query and Criteria Interface
-This interface allows the user to perform queries and also control the flow of
the query execution.
4.
What is a hibernate xml mapping document and how does it look like?
In order to
make most of the things work in hibernate, usually the information is provided
in an xml document. This document is called as xml mapping document. The
document defines, among other things, how properties of the user defined
persistence classes’map to the columns of the relative tables in database.
<?xml
version=”1.0″?>
<!DOCTYPE
hibernate-mapping PUBLIC ”
http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd”>
<hibernate-mapping>
<class
name=”sample.MyPersistanceClass” table=”MyPersitaceTable”>
<id
name=”id” column=”MyPerId”>
<generator/>
</id>
<property
name=”text” column=”Persistance_message”/>
<many-to-one
name=”nxtPer” cascade=”all” column=”NxtPerId”/>
</class>
</hibernate-mapping>
5.
How does hibernate code looks like?
Session
session = getSessionFactory().openSession();
Transaction
tx = session.beginTransaction();
MyPersistanceClass
mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
session.close();
6.
What are the benefits of ORM and Hibernate?
There are
many benefits from these. Out of which the following are the most important
one.
1.
Productivity -Hibernate reduces the burden of developer by providing much of
the functionality and let the developer to concentrate on business logic.
2.
Maintainability -As hibernate provides most of the functionality, the LOC for
the application will be reduced and it is easy to maintain. By automated
object/relational persistence it even reduces the LOC.
3.
Performance -Hand-coded persistence provided greater performance than automated
one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it
is automated persistence then it still increases the performance.
Vendor
independence -Irrespective of the different types of databases
7.
What is meant by full object mapping?
Full object
mapping supports sophisticated object modeling: composition, inheritance,
polymorphism and persistence. The persistence layer implements transparent
persistence; persistent classes do not inherit any special base class or have
to implement a special interface. Efficient fetching strategies and caching
strategies are implemented transparently to the application.
8.
What is a meant by medium object mapping?
The
application is designed around an object model. The SQL code is generated at
build time. And the associations between objects are supported by the
persistence mechanism, and queries are specified using an object-oriented
expression language. This is best suited for medium-sized applications with
some complex transactions. Used when the mapping exceeds 25 different database
products at a time.
9.
What is a meant by light object mapping?
The
entities are represented as classes that are mapped manually to the relational
tables. The code is hidden from the business logic using specific design
patterns. This approach is successful for applications with a less number of
entities, or applications with common, metadata-driven data models. This
approach is most known to all.
10.
What is a pure relational ORM?
The entire
application, including the user interface, is designed around the relational
model and SQL-based relational operations.
This blog is so nice to me. I will keep on coming here again and again. Visit my link as well.
ReplyDeleteHibernate Training in Chennai
Spring Hibernate Training
Hibernate Training in Velachery
Spring Training in Chennai
Spring framework Training
soft skills training in chennai
core java training in chennai
Hibernate Training in Adyar
Unique Information's are here...I am looking for this Piece of information's...Thanks for your Kind Help
ReplyDeleteJava training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery