More interview questions and answers |
---|
Persistence is one of the fundamental concepts in application development. In an object-oriented application, persistence allows an object to outlive the process that created it. The state of the object may be stored to disk and an object with the same state re-created at some point in the future. |
Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. |
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database. |
Hibernate simplifies : |
What are the most common methods of Hibernate configuration? |
The two most common methods of Hibernate configuration are: |
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. |
If your stored procedure is returning a value you can directly use <sql-query>, otherwise you need to use jdbc connection to call the native sql procedure. |
Hibernate supports the feature of lazy initialization for both entities and collections. What this actually means is, the Hibernate engine loads only those objects that we are querying for and doesnt try to fetch other entities(that are associated with the entity we are querying) or collections. |
Proxies are the mechanism that allows Hibernate to break up the interconnected cloud of objects in the database into smaller chunks, that can easily fit in memory. Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. A class can be mapped to a proxy instead to a table. When you actually call load on session it returns you proxy. This proxy may contain actual method to load the data. |
What is the main difference between Entity Beans and Hibernate ? |
In an Entity Bean, we can interact with only one Database at a time. Whereas in Hibernate, we can established the connections to more than one Database. Only thing we need to write one more configuration file. |
The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not threadsafe. 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 ry objects to retrieve persistent objects. |
The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create the SessionFactory, which in turn creates the Session instances. |
Yes! SessionFactory object is threadsafe. Many threads can request for session and immutable cache of compiled mappings for a single database. |
There are four levels defined for ORM quality: |
Hibernate offers a query language which is powerful and provides flexible mechanism to query, store, update and retrieve objects from database. This HQL is an object oriented extension to SQL. Hibernate query Language (HQL) is an object-oriented extension to SQL. |
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 formula attribute of the element. |
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. |
What is the general flow of Hibernate communication with RDBMS? |
The general flow of Hibernate communication with RDBMS is: |
The 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. |
After all mappings have been parsed by the org.hibernate.cfg.Configuration, the application must obtain a factory for org.hibernate.Session instances. This factory is intended to be shared by all application threads: |
There are three types of inheritance mapping in hibernate: |
Hibernate defines and supports the following object states: |
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. |
How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? |
The EmptyInterceptor class provides the isTransient() method to check whether the object is transient or deteched. Method signature: |
Does Hibernate implement its functionality using a minimal number of database queries? |
Hibernate can make certain optimizations implement its functionality using a minimal number of database queries: |
How can we get access to O/R mapping information such as table and column names at runtime? |
This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory. |
No! Hibernate always executes SQL statements using a JDBC PreparedStatement, which allows the database to cache the query plan. There is no reason to avoid the use of generated SQL in modern applications. |
Hibernate supports polymorphic queries and associations in all three inheritance mapping strategies (and even allows mixing of the two most important strategies). |
What are the different Transaction Factories available with Hibernate? |
There are three different types of Transaction Factoryavailable with Hibenate 3.2 are : |
What are the different Fetching Strategies available with Hibernate? |
There are four different Fetching standards available in Hibernate3.2: |
What are the different types of statistics available in Hibernate 3.2? |
Different types of statistics available in Hibernate: |
How can multiple threads access session factory simulteneously to create session instance? |
We know that the session factory is thread-safe, so it is okay to use SessionFactory object by many threads to have session from session factory, but I think session is not thread safe and it should be used by one thread at a time, and after use, session has to be flushed and closed. |
HQL (Hibernate Query Language) is fully object oriented, with support for object inheritence, polymorphism and association, but SQL (Structure Query Language) is more of Relational with structured form of queries. |
Difference between session.update() and session.lock() in Hibernate ? |
Both the session.update() and session.lock() are intended for re-attaching 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. |
What is the best application framework for use with Hibernate? |
Both the session.update() and session.lock() are intended for re-attaching 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. |
Dirty checking feature of the Hibernate allows users or developers to avoid time consuming database write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. |
Hibernate can be configured with two types of files out of which hibernate.cfg.xml is the mapping description file in which Hibernate uses to configure its functions. This mapping file has an extension *.hbm which instructs mapping between Java class and database tables. The usage of mapping description file rests entirely upon the business entity. |
Both load() and get() methods used to find out the object in cache or database. Use get() method if you are not sure that the object exists. The get() method will return null if the unique id is not found in the database. The get() will hit the database immediately. |
The Transaction interface provides methods for declaring the boundaries of a database transaction. |
What auto commint mode should you use in JDBC connection in Hibernate? |
A magical setting that is often a source of confusion is the JDBC connection\'s auto commit mode. If a database connection is in auto commit mode, the database transaction will be committed immediately after each SQL statement, and a new transaction will be started. This can be useful for ad hoc database queries and ad hoc data updates. |
What are the various advanced configuration techniques in Hibernate? |
Advanced configuration techniques in Hibernate: |
A JNDI bound Hibernate SessionFactory can simplify the lookup of the factory and the creation of new Sessions. If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (eg. java:comp/env/hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. When binding the SessionFactory to JNDI, Hibernate will use the values of hibernate.jndi.url, hibernate.jndi.class to instantiate an initial context. If they are not specified, the default InitialContext will be used. |
JMX is standard API for managing the Java application and components. JMX is a management technology that can be used to manage any kind of resource. The JMX technology provides the tools for building distributed, Web-based, modular and dynamic solutions for managing and monitoring devices, applications, and service-driven networks. |
CaveatEmptor\'s primary purpose is to educate on how to build a persistence service/layer with Hibernate. CaveatEmptor is an online auction application with business objects such as Item, User, and Bid. The domain model covers various kinds of entities, entity associations and collections. The Caveat Emptor is a simple book auction application built with XUI 3.1. It shows how to use the Hibernate POJO support in a two tiered scenario, where the Hibernate serves as a persistence layer (it is being used to directly connect to the database). |
How will you map the metadata in configuration file in Hibernate? |
In Hibernate 2.x, mapping metadata is most of the time declared in XML text files. Another option is XDoclet, utilizing Javadoc source code annotations and a preprocessor at compile time. The same kind of annotation support is now available in the standard JDK. |
What are the Transparent and Automated persistence in Hibernate? |
Hibernate provides automatic and transparent object/relational mapping making it a snap to work with SQL databases in Java applications. |
XDoclet is an open source code generation engine. It enables Attribute-Oriented Programming for java. In short, this means that you can add more significance to your code by adding meta data (attributes) to your java sources. This is done in special JavaDoc tags. |
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. |
Where should SessionFactory be placed so that it can be easily accessed? |
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 the different types of property and class mappings? |
The different types of property and class mappings: |
There are three methods by which an object can be identified: |
Associations are used to represent relationships between classes. Managed association means that, if a change is made to one end of the association, it will be reflected at the other end. So when changes are made to the attributes participating in this association, they will be reflected at the other end automatically. The developer doesn\'t have to mange the associations manually. Hibernate mainly supports two types of associations: |
What are the Extension interfaces that are there in hibernate? |
There are many extension interfaces provided by hibernate: |
There are mainly two types of environments in which the configuration of hibernate application differs: |
What is the file extension you use for hibernate mapping file? |
The file extension you use for hibernate mapping file is \"filename.hbm.xml\". |
Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. Look how a SessionFactory is created when we use method chaining. |
Hibernate exposes database identity to the application in two ways: |
A major objective of the Hibernate project is support for fine-grained object model. Fine-grained means \"more classes than tables\". |
What are the types of mapping class inheritance in Hibernate? |
There are three different approaches to representing an inheritance hierarchy: |
What are the various services provided by the Persistence manager? |
Any transparent persistent tool includes a persistence manager API, which usually provides services for: |
By using the session.merge() method call, you can reatach detached objects to a session when the same object has already been loaded into the session. |
The general considerations or best practices for defining your Hibernate persistent classes are: |
What is the difference between sorted and order collection in Hibernate? |
A sorted ordered collection is stored in memory using Java Comparetor, whereas ordered collection is stored at the database level using orderby clause. |
The main advantage of using Hibernate over sql is that Hibernate avoids writing huge queries. Because most of the work is taken care by mapping and also criteria class is very useful for complex joins. We can also avoid JDBC API by using Hibernate. |
The id field in hbm.xml file is used to specify the primary key in database. We can also use generator to specify the way primary key is generated to the database. |
Hibernate uses POJO classes for handling persistence, these classes need to adhere normal bean writing. Beans are at form (view) level and Hibernate are at database level. |
What are the various ways to fetch objects from database in Hibernate? |
Hibernate provides the following ways to get objects out of the database: |
How will you retrieve an object by Identifier from the database in Hibernate? |
The following Hibernate code snippet retrieves a User defined Object form the database: |
The HQL is an object oriented dialect of the familiar relational query language SQL. HQL is not a data manipulation language like SQL. It\'s used only for object retrieval, not for updating, inserting, or deleting data. HQL supports: |
The Hibernate Query By Criteria API lets you build a query by manipulating criteria objects at runtime. This approach lets you specify constraints dynamically without direct using mainpulations, but it doesn\'t lose much of the flexibility or power of HQL. |
The idea behind Query By Example is that the application supplies an instance of the queried class with certain property values set. The query returns all persistent instances with matching property values. QBE isn\'t a particularly powerful approach, but it can be convenient for some applications. The following code snippet demonstrates a Hibernate QBE: |
What are the various fetching strategies from the database in Hibernate? |
Hibernate allows you to choose among four fetching strategies for any association, in association and at runtime: |
Eager or outer join fetching lets you explicitly specify which associated objects should be loaded together with the referencing object. Hibernate can then return the associated objects in a single database request, utilizing an SQL OUTER JOIN. |
When a client request an entity and its association graph of object from the datebase. It isn\'t usually necessary to retrieve the dwhole graph. |
A proxy or collection wrapper is automatically initialized when any of its methods are invoked. However it is only possible to initialize a proxy or collection wrapper if it\'s currently associated with an open session. If you close the session and try to access an uninitialized proxy or collection, Hibernate throws a runtime exception. |
Difference between getCurrentSession() and openSession() in Hibernate ? |
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 getCurrentSession() method looks at the current context to see if a session is stored in there. If there is one, it uses it, and if there isn\'t a session in the current context, it creates a new one and saves it in there. |
The types of Collection in Hibernate: |
What is the difference between JDBC and JTA transactions in Hibernate? |
In a non-managed environment, the JDBC API is used to mark transaction boundaries. You begin a transaction by calling setAutoCommit(false) on a JDBC connection and end it by calling commit(). You may, at any time, force an intermediate rollback by calling rollback(). |
What are the various transaction isolation isssues in Hibernate? |
The ANSI SQL standard defines the standart transaction isolation levels in terms of which of these phenomenon are permissible: |
When one transaction reads changes made by another transaction that hasn\'t yet been committed is called dirty read. This is very dangerous, because those changes might later be rolled back. |
Describe the various isolation levels defined by ANSI SQL standart? |
The standart isolation levels are defined by the ANSI SQL standard but aren\'t particular to SQL databases: |
A transaction executes a query twice, and the second result set includes rows that weren\'t visible in the first result set. This situation is caused by another transaction inserting new rows between the execution of the two queries. |
How will you set the isolation level for database in JDBC connection? |
Every JDBC connection to a database uses the database\'s default isolation level, usually read committed or repeatable read. This default can be changed in the database configuration. You may also set the transaction isolation for JDBC connection using a Hibernate configuration option: |
Catching is such a fundamental concept in object/ralational persistence that you can\'t understand the performance, scalability, or transactional semantics of an ORM implementation without first knowing what kind of catching strategy it uses. There are three types of cache: |
What are the various built-in concurrency strategies for transaction used in Hibernate? |
A concurrency strategy is a mediator, it\'s responsible for storing items of data in the cache and retrieving them from the cache. There are four built in concurrency strategies, representing decreasing levels of strictness in terms of transaction isolation: |
What are the various built-in-mapping types available in Hibernate? |
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: |
When we use word associations, we are always referring to relationships between entities. The various mapping association in Hibernate: |
Which interfaces are defined to execute the query in the Hibernate? |
The following interfaces are defined to execute the query: |
In Hibernate queries, you don\'t usually specify a join condition explicitly. Rather you specify the name of a mapped Java class association. |
In HQL, you can specify that an association should be eagerly fetched by an outer join using the fetch keyword in the \'from\' clause: |
What are the different caching services provided by the Hibernate? |
Hibernate supports four different caching services. EHCache (Easy Hibernate Cache) is the default service. If you prefer to use an alternative cache, you need to set the cache.provider_class property in the hibernate.cfg.xml file: |
Advantages of Hibernate: |
Joined subclasses are those that are mapped to a table-per-subclass design rather than a table-per-hierarchy. |
The Configuration class kicks off the runtime portion of Hibernate. It\'s used to load the mapping files and create a SessionFactory for those mapping files. There are three ways to create and initialize a Configuration object. |
Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database connections that are reused. Application servers often provide their own connection pools using a JNDI DataSource, which Hibernate can take advantage of when configured to use a DataSource. |
You can mark the class as mutable=\"false\", Default value is true. This specifies that instances of the class are mutable. You can not update or delete immutable classes by the application. |
What is the use of dynamic-insert and dynamic-update attributes in a class mapping? |
You may declare a persistent class using the class element. The dynamic-insert and dynamic-update attributes are optional attributes. The dynamic-update (defaults value is false), specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed. |
There are three types of instance states in Hibernate: * 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 happens when both hibernate.properties and hibernate.cfg.xml are in the classpath? |
The settings of the XML configuration file will override the settings used in the properties. |
The org.springframework.orm.hibernate.HibernateTemplate class simplifies Hibernate data access code, and converts checked HibernateExceptions into unchecked DataAccessExceptions, following the org.springframework.dao exception hierarchy. Uses the same SQLExceptionTranslator mechanism as JdbcTemplate. |
@Entity :-This annotation is used to make a entity (model) class. The annotation in javax.persistence.Entity class. @Table:-Used to map table name with POJO @Id :-Is used to make primary key column.Table must have a primary key without primary key we cant map . @Column :-map column name with java POJO property e.g. import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="BORROWER_PERSON_DETAILS") public class BorrowerPersonDetail { @Id @Column(name="BORROWER_PERSON_REF_ID") private String borrowerPersonRefId; @Column(name="BORROWER_REF_ID") private String borrowerRefId; public String getBorrowerPersonRefId() { return this.borrowerPersonRefId; } public void setBorrowerPersonRefId(String borrowerPersonRefId) { if(borrowerPersonRefId!=null) this.borrowerPersonRefId = borrowerPersonRefId; } public String getBorrowerRefId() { return this.borrowerRefId; } public void setBorrowerRefId(String borrowerRefId) { if(borrowerRefId!=null) this.borrowerRefId = borrowerRefId; } } Here we had created a POJO class named BorrowerPersonDetail to map is with table named BORROWER_PERSON_DETAILS . This having two columns 1.BORROWER_PERSON_REF_ID is primary key And 2. BORROWER_REF_ID . We are making there two columns with borrowerPersonRefId and borrowerRefId |
Hibernate provide key features of it thats why it is good to use hibernate. Performance: Hibernate can save your time and efforts, and it can let you achieve some performance gains that you could hardly ever achieve by hand-coding. Portable: Application portability is a key feature in Hibernate it allows developers to port applications to almost all SQL databases. data query and retrieval is possible with hibernate. Set of objects: Hibernate is set of objects we dont need to learn SQL ,here we can treat table as object. In case of JDBC we need to learn SQL. Fast development: Development fast in case of Hibernate because you dont need to write queries. Get benefit of Cache: Hibernate support 2 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. Open source code :- As open source so no need to pay. |